I am attempting to have my Java program write its output to a geoJSON file. Something like the following works well
JSONArray coord = new JSONArray("["+obj.getLng()+","+obj.getLat()+"]");
point.put("coordinates", coord);
generates the following correct JSON String
"coordinates":[-105.93879779882633,36.29086585830942]
However, I would also like to include lines (and polygons) in my output. These are defined as collections of coordinates, such that the resulting string looks something like this
"coordinates":[[-106.0,36.0],[-105.96856743366506,36.0],[-105.93713486733012,36.0]]
I am attempting to read a collection of points that define my line into a JSONArray. However, no matter what I do, there ends up being extra quotation marks in my final JSON String. Something like
"coordinates":["[-106.0,36.0],[-105.96856743366506,36.0],[-105.93713486733012,36.0]"]
if I try to use StringBuilder to build out the exact content of the string I would like the coordinates value to hold. If I attempt to create an array of coordinate arrays and give that to the JSONArray constructor, I simply end up with each coordinate pair in quotation marks instead.
My question is: Why is it that using StringBuilder or other methods to create my JSONArray leads to this result, but directly passing in a String to the new JSONArray constructor does not? The JSONArray constructor seems perfectly capable of interpreting
new JSONArray("["+obj.getLng()+","+obj.getLat()+"]");
correctly, but falls apart when I say
StringBuilder builder = new StringBuilder();
for (Obj obj : objs) {
builder.append("["+obj.getLng()+","+obj.getLat()+"]");
}
new JSONArray(builder.toString());
This seems like a trivial problem, so the solution to my issue is likely simple, but I would particularly like help in understanding why this is the case.
Example:
JSONObject point = new JSONObject();
JSONArray coord = new JSONArray("["+150+","+30+"]");
point.put("coordinates", coord);
System.out.println(point.toString());
results in
{"coordinates":[150,30]}
however
JSONObject lineString = new JSONObject();
String[] coords = {"["+150+","+30+"],["+160+","+40+"],["+170+","+50+"]"};
JSONArray coord = new JSONArray(coords);
lineString.put("coordinates", coord);
System.out.println(lineString.toString());
results in
{"coordinates":["[150,30],[160,40],[170,50]"]}
The issue is the quotation marks surrounding the cords string array ({"coordinates":[-->"[150,30],[160,40],[170,50]"<--]})
coords needs to just be a JSONArray as a string.
There's not extra quotes. You've made a list of one string.
So like
String coords = "["+150+","+30+"]";
JSONArray coordArray = new JSONArray(coords);
Which seems to match your first example, and that is correct, so I don't see the confusion since you're doing different things.
Anyways, it would be best to use the JSONArray methods to build the array rather than messing with string concatenation.
In your sample, A JSONArray contains many other JSONArray.
So we have to write code accordingly.
E.g.:
JSONArray cooord = new JSONArray();
for (Obj obj : objs) {
JSONArray temp = new JSONArray();
temp.put(obj.getLng());
temp.put(obj.getLat()+);
cooord.put(temp);
}
System.out.println(cooord);
Related
i have some parse code and to parsed JSONObject i need to add one more JSONObject, but getting error Unexpected token LEFT BRACE({), because my code creating multiply JSONObjects in file, not at parsed JSONObjec. Here is a code, that creating object
aJson = (JSONObject) parser.parse(reader);
JSONObject json = new JSONObject();
JSONArray blockData = new JSONArray();
for(Block b : blocks){
json.put("player-name", p.getName());
json.put("uuid", p.getUniqueId().toString());
json.put("nearestPlayers", new JSONArray());
blockData.add(b.getLocation().getWorld().getName());
blockData.add(b.getLocation().getWorld().getEnvironment());
blockData.add(b.getLocation().getX());
blockData.add(b.getLocation().getY());
blockData.add(b.getLocation().getZ());
}
aJson.put(blockData, json);
Here is JSON
{"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}} //here is that part// {"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"},"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}}
In JSON array values must be of type string, number, object, array, boolean or null. Arrays hold values of the same type and not different types.
Looking at your code the array is an array of objects. So you would have to create an object and add the values before adding to the array.
Don't directly add values to the array but create an object and then add to the array.
Your code is wrong. To put an object into JSONObject please read this document
In your case, you need to convert blockData to String to put in the JSONObject.
It's like this: aJson.put(blockData as String, json);
Hope it can be helpful to you.
I'm exporting some data in java using JSON then I'm reading that data and trying to get elements from an array inside the JSON object but I'm having issues.
I have tried a lot of things like
jsonObject.get("InGameCord").get("x")
Object Testo = jsonObject.get("InGameCord");
Testo.x
Things like that along with more that did not work so deleted the code.
This is the exported JSON file and im trying to access the InGameCord array X or Y.
{"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}
Here is my file reader code
FileReader reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
System.out.println("BaseName: "+jsonObject.get("BaseName"));
System.out.println("BaseID: "+jsonObject.get("BaseID"));
System.out.println("InGameCord: "+jsonObject.get("InGameCord"));
All of this works and exports the correct info.
So I'm trying to get let us say the X value of InGameCord.
int X = 463;
Given your JSON data {"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}:
"InGameCord" is the name of an array which can be instantiated as a JSONArray.
That array contains only one element: {"x":463,"y":451}.
That array element can be instantiated as a JSONObject. It contains two name/value pairs:
"x" with the value 463.
"y" with the value 451.
So based on the code you provided, to instantiate the JSONArray:
JSONArray numbers = (JSONArray) jsonObject.get("InGameCord");
To retrieve the first (and only) element of the array into a JSONObject:
JSONObject jObj = (JSONObject) numbers.get(0);
To get the value for "x" into an int variable cast the Object returned by get() to a Number, and then get its intValue():
int value = ((Number) jObj.get("x")).intValue();
You can even do the whole thing in one line, but it's ugly:
int y = ((Number) ((JSONObject) numbers.get(0)).get("y")).intValue();
I have this code:
String sURL = "https://example.com/json"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
String names = rootobj.get("names").getAsString();
System.out.println(names);
How can I access the second level of the array in the second to last line? "names" ist the first dimension whichs works fine.
In PHP the solution would be
$var = json[...][...] //for accessing the second dimension.
How is this done in Java? Something like rootobj.get("names/surname") doesn't work.
In your Github link, your root element is an array, not an object. (And there's no names attribute)
So you need
root.getAsJsonArray();
Then you would loop over the length of this array, and use a get(i), to access a particular object.
From that object, use another get method to access one attribute of it
According to your code, I assume you use GSON for JSON processing. If your JSON element is an array, you can simply access its elements using get(index). Sketched here:
//Not taking care of possible null values here
JsonObject rootobj = ...
JsonElement elem = rootobj.get("names");
if (elem.isJsonArray()) {
JsonArray elemArray = elem.getAsJsonArray();
JsonElement innerElem = elemArray.get(0);
if (innerElem.isJsonArray()) {
JsonArray innerArray = innerElem.getAsJsonArray();
//Now you can access the elements using get(..)
//E.g. innerArray.get(2);
}
}
Of course this is not that nice to read. You could also take a look at JsonPath, which simplifies navigating to specific parts in your JSON documents.
Update:
In the document you referred to, you want to extract which value exactly? The id value of the array elements (according to one of your comments)? This could be done like this for this example here:
JsonElement root = jp.parse....
JsonArray rootArray = root.getAsJsonArray(); //Without check whether it is really an array
//By the following you would extract the id 6104546
//Access an other array position if you want the second etc. element
System.out.println(rootArray.get(0).getAsJsonObject().get("id"));
Otherwise please explain in more detail what exactly you want (the code you posted does not match with the json examples you refer to).
In my application, I need to pass JSON array to java then convert that array to java array using java as a language. Here is the code.
JavaScript
function arraytofile(rans)
{
myData.push(rans); // rans is the random number
var arr = JSON.stringify(myData);// converting to json array
android.arraytofile(arr); // passing to java
}
Java
public void arraytofile(String newData) throws JSONException {
Log.d(TAG, "MainActivity.setData()");
System.out.println(newData);
}
newData is printing data as [[2],[3],[4]]... I want in regular java array. How I can achieve this?
You can use Google gson . An excellent Java library to work with JSON.
Find it here: https://code.google.com/p/google-gson/
Using gson library classes you can do something like this:
// I took a small sample of your sample json
String json = "[[2],[3],[4]]";
JsonElement je = new JsonParser().parse(json);
JsonArray jsonArray = je.getAsJsonArray();
// I'm assuming your values are in String, you can change this if not
List<String> javaArray = new ArrayList<String>();
for(JsonElement jsonElement : jsonArray) {
JsonArray individualArray = jsonElement.getAsJsonArray();
JsonElement value = individualArray.get(0);
// Again, I'm assuming your values are in String
javaArray.add(value.getAsString());
}
Now you have your json as Java List<String>. That's basically as array.
If you know exact number of results, you can surely define an array of fix size and then assign values to it.
If you know Java, than you already know how to go from here.
I hope this helps.
I know php a little. and java much little.
I am creating a small application to search a text in a text area and store the result in a array.
The array in PHP will look like this.
array(
"searchedText" => "The text that is searched",
"positionsFound" => array(12,25,26,......),
"frequencies" => 23 //This is total words found divided by total words
);
But, java does not support array with multiple data types. In the above array, only the second element "positionFound" is of variable length.
Later on I need to iterate through this array and create a file including all above mentioned elements.
Please guide me
Java does support Objects. You have to define a Class like
class MyData {
String searchedText;
Set<Integer> positionsFound;
int frequencies;
}
List<MyData> myDataList = new ArrayList<MyData>();
// OR
MyData[] myDataArray = new MyData[number];
And you can use this structure to hold your data. There are other methods which are helpful such as constructors and toString() and I suggest you use your IDE to generate those.
When writing this data to a file, you might find JSon a natural format to use.
I suggest you look at GSon which is a nice JSon library.
From the GSon documentation, here is an example
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj