How to check a List is empty or not when it contains empty Json object.
Below is the example:
"data": {"parseList" : [{}]}
now I want to check parseList is empty or not , I tried using
collectionUtils.isEmpty(parseList);
but it is not working any help is appreciated.
You can use length() method of JSONObject which returns the count of key-value pairs inside a JSONObject.
So you can find out if your object is empty or not.
You can parse Json using org.json and obtain JsonArray object. The length() method could be used to find the number of elements inside JsonArray.
String stringToParse = "";
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
JSONArray array = myjson.getJSONArray("parseList");
System.out.println(array.length());
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 have the following JSON:
[{
"aaa": "blah",
"ddd": 2
}]
Note that the map is inside an array. How to get the map and then the value of "aaa".
Using Json Simple.
Thanks!
The following code should work. Let me know if it doesn't!
Object obj = JSONValue.parse(jsonString);
JSONArray array = (JSONArray)obj;
JSONObject obj2 = (JSONObject)array.get(0);
String result = obj2.get("aaa")
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).
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!