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).
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 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);
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've got a JSON string and I'm just trying to access the different properties of it and store them in Java variables. However, I keep getting an exception with the following code:
private JSONObject jObj;
private String jString;
//...
jString = result; //this is my JSON string passed from another activity
try {
jObj = new JSONObject(jString);
//int eventID = jObj.getInt("eventID");
} catch (JSONException e) {
Toast.makeText(searchResultsActivity.this, "Search results failed!", Toast.LENGTH_SHORT).show();
finish();
}
Yes I have the required imports. I've displayed jString on its own to confirm that it's valid JSON. I'm kind of lost because this seems to be the most basic thing I need to do. Thanks for any help guys.
EDIT - here is an example JSON string:
[{"eventID":"47","event_name":"test","event_address":"Test","event_duration":"3","event_date":"20110527","event_time":"1347","event_description":"Test","num_attending":"1"}]
This string is received through a PHP script where I do echo json_encode($array), where $array is the associative array creating this JSON response.
The exception I get is:
"org.json.JSONException: Value[//above JSON string//] of type org.json.JSONArray cannot be converted to JSONObject"
Eclipse did not tell you because you were trying to create a JSONObject from a JSONArray:
JSONArray jArr = new JSONArray (jString);
int eventID = jArr.getJSONObject(0).getInt("eventID");
To answer your last comment (why is this?):
From the (original documentation](http://www.json.org/java/index.html):
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
Since you were parsing a string that started with square brackets instead of curly braces, you need to parse it as a JSONArray. In your case, it is an array of size 1.
You are trying to parse a JSONArray as a JSONObject
JSONArray jarray = new JSONArray(jString);
gl!