I'm currently confused why I cannot pull a JSONArray from a JSONArray in my android application. An example and a snippet of my source code are given below.
//The JSON
{
"currentPage":1,
"data":[
{
"id":"dimtrs",
"name":"Bud Light",
"breweries":[
{
"id":"BznahA",
"name":"Anheuser-Busch InBev",
}
]
}
],
"status":"success"
}
Now I'm trying to retreive the "breweries" array.
//Code Snippet
...
JSONObject jsonobject = new JSONObject(inputLine);
JSONArray jArray = jsonobject.getJSONArray("data");
JSONArray jsArray = jArray.getJSONArray("breweries");
...
I can pull objects out of the data array just fine, but I cannot get the "breweries" array from the "data" array using my current code.
The error for jsArray is:
The method .getJSONArray(int) in the type JSONArray is not applicable for the arguments String
So what is the correct way to pull the "breweries" array out of the "data" array?
Thanks for the help in advance!
It is because "breweries" is in the 1st object of the "data" array, not directly on the array itself. You are trying to get a key from an array.
So you want to call jArray.getJSONObject(0).getJSONArray("breweries"); or something to that effect.
As Sambhav Sharma explains in a comment, the reason for the error is that get methods for JSONArray expect an int and not a String as their argument.
Related
[Java 17 using the org.json parsing library. Not able to switch to Gson because I've written an insane amount of code in org.json :/ ]
Hello!
I am using an API in Java with the org.json JSON parsing library. I need to get the value of an unnamed JSON object in an array.
{
"lorem": [
{ // this object needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
},
{ // this object also needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
},
{ // this object needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
}
]
}
Note that the entire JSON file is NOT an array, there is just one JSON array inside of a JSON object. How would I be able to get the value of all of these unnamed fields inside of the array?
Thanks in advance for any help, and also sorry if this question has been asked before, I wasn't able to find anything on it when I searched for it on Stackoverflow.
Those objects aren't really unnamed objects, they are part of an JSON array. Because they are contained in an array, we can iterate through that array and we can retrieve every object by index.
Assuming that the we read the json provided above from a file:
public static void main(String[] args) throws FileNotFoundException {
String resourceName = "src/main/resources/input.json";
InputStream inputStream = new FileInputStream(resourceName);
JSONTokener jsonTokener = new JSONTokener(inputStream);
JSONObject jsonObject = new JSONObject(jsonTokener);
// Get the array named lorem from the main object
JSONArray jsonArray = jsonObject.getJSONArray("lorem");
// Iterate through the array and get every element by index
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println("ipsum:" + object.get("ipsum"));
System.out.println("sit:" + object.get("sit"));
System.out.println("consectetur:" + object.get("consectetur"));
}
}
Also, JSONObject has a toList method, which returns a List<Object>.
I am using the following libraries to create some JSON object.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
The json I am trying to create is this:
{
"function": "create_contact_group",
"parameters": [{
"user_id": "teer",
"comp_id": "97",
"contact_group_name": "Test01",
"invite_user_list": [{
"invite_user_id": "steve"
}]
}]
}
My function looks like this:
public JSONObject createJSONRequest() {
/* Create json object */
JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("user_id", "teer");
map.put("comp_id", "97");
map.put("contact_group_name", "Test01");
List<String> mInviteUserList = new ArrayList<>();
mInviteUserList.add("steve");
/* Create the list of invitee */
Map<String, String> inviteList = new HashMap<>();
for(String user : mInviteUserList) {
inviteList.put("invite_user_id", user);
}
/* Add the invitees into the json array */
JSONArray inviteArray = new JSONArray();
inviteArray.add(inviteList);
/* Add the json array to the json object */
jsonObject.put("invite_user_list", inviteArray);
JSONArray parameterlist = new JSONArray();
parameterlist.add(map);
parameterlist.add(jsonObject);
jsonObject.put("parameters", parameterlist);
jsonObject.put("function", "create_contact_group");
Log.d(TAG, "jsonObject: " + jsonObject.toJSONString());
return jsonObject;
}
However, the function crashes when I get to the following line:
Log.d(TAG, "jsonObject: " + jsonObject.toJSONString())
I think it has something to do with this line here:
parameterlist.add(jsonObject);
Stacktrace:
java.lang.StackOverflowError java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95) at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:132)
at java.lang.StringBuffer.append(StringBuffer.java:126) at org.json.simple.JSONValue.escape(JSONValue.java:266) at org.json.simple.JSONObject.toJSONString(JSONObject.java:116)
Many thanks for any suggestions,
There are a couple of issues in your code.
One issue is that the structure you create in the java code will not match the structure that you show above. This I will try to describe a bit below.
The second issue is that you get a stackoverflow exception (which you know but don't know why).
The stackoverflow exception is thrown cause the program runs out of the stack memory assigned by the computer. Why you ask? Well, cause you create a recursive or cyclic JSON object.
This isn't good, but its not that big a deal cause its kinda easy to fix.
So why does the program throw this exception? Well, look at the following snippet:
JSONArray parameterlist = new JSONArray();
parameterlist.add(map);
parameterlist.add(jsonObject);
jsonObject.put("parameters", parameterlist);
jsonObject.put("function", "create_contact_group");
You create a JSONArray and then add the JSONObject created before to the array.
After that you add the same array to the object that is already in the array.
I expect that you see the issue with that!
So, that should not be done.
And how to fix this? Well, I kinda think its better that I describe how you should write the code to get the structure you are actually asking for, so I'll try do that...
What to do...?
A JSON (JavaScript Object Notation) -object is always declared with this type of brackets: {} a JSON array with [], so, the JSON you are trying to generate should be in the following data types:
{ // <= Root object (a JSON-object).
"function": "create_contact_group", // <= Key in the root-object (where the key is a string and the value a string)
"parameters": [ // <= Key in the root-object (where the key is a string and the value is an array.
{ // <= Object inside the array.
"user_id": "teer", // Key (string/string)
"comp_id": "97", // Key (string/string)
"contact_group_name": "Test01", // Key (string/string)
"invite_user_list": [ // Key (string/array)
{ // Object inside the invite_user_list array
"invite_user_id": "steve" // Key (string/string)
}
]
}
]
}
So when creating the JSON-object in java, you will want to create a root object then add all the diff params inside it.
Adding a value to a JSONObject is done with the JSONObject.put(string, Object) method, where the string is a key and the object a value.
So to start, I would recommend creating the parameters list.
In your case, you use a HashMap for the objects, which is not really wrong, but not really necessary either, I would just stick to a JSONObject, which is not all that different than a HashMap<string, Object>.
So instead of map.put(...), you could do something like:
JSONObject param = new JSONObject();
param.put("user_id", "teer");
param.put("comp_id", "97");
param.put("contact_group_name", "Test01");
Now, one of the objects values should be an array (invite_user_id) and the easiest way to add an array to the object is to create a JSONArray and then just add it.
JSONArray inviteList = new JSONArray();
// Then you need to add an object to the array for each `user` that has invited.
// For-loop here maybe?
JSONObject invitee = new JSONObject();
invitee.put("invite_user_id", user);
inviteList,add(invitee); // This will make it into an array with objects, I.E., [ { "invite_user_id": "Steve" } ]
After creating the invite list, add it to the param object like:
param.put("invite_user_list", inviteList);
// Now, param should be in its own list too, so you should probably create a JSONArray for the params.
// Ill leave that to you, and we pretend we have a list of the param objects named "params".
And then at the end, you create the root object and set its values:
JSONObject root = new JSONObject();
root.put("parameters", params);
root.put("function", "create_contact_group");
And that should be it.
This should create a JSON-string with the structure that you made above. But I would recommend testing (and writing unit tests!) for this (especially as I have written this code in the browser!).
But why?!
I guess I should try to describe why your code was not working as the one I described above.
You start by creating a root object, so far so good (can create it at start or at the time you need it, doesn't really matter), after that you create a HashMap and add the properties to it.
So far this is also legit (you could later create a JSONObject from the map).
In the next part, you create an ArrayList (im not really sure why) and add a name to it, and then another HashMap which you add the single name to (key invite_user_list) inside a for-loop.
This is either not necessary (cause its just one name) or wrong (if there is supposed to be more names in a real life execution of the code), in case of unnecessary, the for-loop shouldn't be there and in case of "not like real life" it should not be added to a Map!
Instead the invieList should have been an array, and each entry added should have been a object which had the "invite_user_id" key set to the name.
After that, you add the inviteList HashMap to a newly created JSONArray, I guess this could be kinda okay, if you only want one object ever in the array, else I would recommend creating it before the loop and add each entry into it!
The inviteArray is then put inside the root object with the key invite_user_list, after that you create another JSONArray and add both the map (your parameters created at the start) and the JSONObject (root) created first of all.
But the thing you do after that, is why you are getting a stackoverflow exception, you add the parameterlist (which contains the jsonObject (root)) to the jsonObject, which makes the jsonObject exist inside an array that is inside itself!
This creates a cyclic JSON structure which will never end if the whole thing was to be unrolled, hence the computer throws the exception.
The structure of the resulting object would also be wrong, cause it would look something like this:
{ // Root (jsonObject)
"invite_user_list": [
{ "invite_user_id": "steve" }
]
"parameters": [
{ // The "map" hashmap
"user_id", "teer",
"comp_id": "97",
"contact_group_name": "Test01"
},
{ // The jsonObject object (which is also the root!)
"invite_user_list": [
{ "invite_user_id": "steve" }
],
"parameters": [
{ // The "map" hashmap
"user_id", "teer",
"comp_id": "97",
"contact_group_name": "Test01"
},
{
// The jsonObject object again (which is also the root and the parent!)
// ... and so on til eternity!
}
],
"function": "create_contact_group"
}
],
"function": "create_contact_group"
}
Extra...
I would like to add here at the end (where I hope you end up after reading the whole wall of text that I wrote above, cause you might have learnt something!) that there is a easier way of doing it.
Now, I haven't used this lib myself, but from what I understand, it should be able to serialize a whole object, the lib can be found at Googles github repos which can be used as a json serializer and convert a class-instance to a json string, then you could just create a class for the whole object and fill it up and serialize it at the end of the function, without using either JSONArray nor JSONObject.
The issue is due to recursion process that occurs when you are trying to add the JsonObject to JsonArray and viceVersa.
The thing you are doing is,
JSONArray parameterlist = new JSONArray();
parameterlist.add(map);
parameterlist.add(jsonObject);
And then
jsonObject.put("parameters", parameterlist);
The problem is when you print the object using jsonObject.toJSONString(), Then at first it will fetch the parameterlist then as jsonObject is part of the keyvalue pair on the parameterlist JsonArray it will refetch the jsonObject which then again fetch the parameterlist and this process continues on and hence causing the StackOverflow Issue.
The Quick Solution is to create new JsonObject while assigning the parameterList,
JSONArray parameterlist = new JSONArray();
parameterlist.add(map);
parameterlist.add(jsonObject);
JSONObject newJson = new JSONObject();
newJson.put("parameters", parameterlist);
System.out.println(newJson.toJSONString());
A variable called wrongAnswers which is an array of javascript objects is generated on the client.
It has the form
wrongAnswers = [
{"wrongAnswer": "Manzana", "wrongQuestion": "apple"},
{"wrongAnswer": "arbol", "wrongQuestion": "tree"}
]
JSON.stringify(wrongAnswers) is used and the variable is then sent to a servlet using a form.
Once it is in the servlet, i want to convert the JSON into a Java Arraylist.
I have a class Answer with 2 variables, wrongAnswer and wrongQuestion. I would like to iterate through the JSON array, and for each object, create an Answer object with the value of wrongAnswer and wrongQuestion in that JSON Object. Each time, adding the Answer object to an ArrayList so in the end, i have an ArrayList of Answers corresponding to all the values from the JSON.
At the moment, I can use request.getParameter("json") which gets me a String with the JSON data. However, i am not sure what to do with this String.
Is there a way i can easily convert a String holding JSON data into a JsonArray or JsonObject, which i can easily iterate through, getting the value of the name: value pairs in each object?
Some example code would have been nice, but there is many ways to parse and work with JSON.
One way you could try is:
JSONArray json = new JSONArray(jsonString);
ArrayList<String> array = new ArrayList<String>();
for(int index = 0; index < json.length(); index++) {
JSONObject jsonObject = json.getJSONObject(index);
String str= jsonObject.getString("wrongAnswer");
array.add(str);
}
Try using jackson for parsing the json string: https://github.com/FasterXML/jackson
For an example, look up: How to parse a JSON string to an array using Jackson
Following code produces a nested array as a result for keys containing three items:
import org.codehaus.jettison.json.JSONObject;
// ...
JSONObject ret = new JSONObject();
for (Key key:keys) ret.append("blocked",key.id());
The result is:
{"blocked": [[["1"],"2"],"3"]}
Is this expected? If it is, how can I construct a plain array adding item by item?
You need to create a JSONArray object:
JSONObject ret = new JSONObject();
JSONArray arr = new JSONArray();
arr.put("1");
arr.put("2");
arr.put("3");
ret.put("blocked", arr);
The result is:
{"blocked":["1","2","3"]}
It's curious because the API says the following:
Append values to the array under a key. If the key does not exist in the
JSONObject, then the key is put in the JSONObject with its value being a
JSONArray containing the value parameter. If the key was already
associated with a JSONArray, then the value parameter is appended to it.
But it doesn't work correctly. When I do:
JSONObject o = new JSONObject();
o.append("arr", "123");
o.append("arr", "456");
I get an Exception saying that "JSONObject[arr] is not a JSONArray". It looks like there is a bug.
I ran into a similar problem. You should use the put method; not the append method. And, of course, you should create a JSONArrray and use that as the second argument of the put method.
When i call server its response is based of json object. Actually, I know how to parse JSON object but this response is strange for me. Server response is:
{"body":"Not Available!","clazz":"SoccerMatchPreview","id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978},"publishedDate":"2012-06-08 17:00:00 +0100","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595","title":"Poland vs Greece"}
Those Information that I need are body, publishedDate, refKey and title. The code that i have written based of JSON object is this:
JSONObject jObject = new JSONObject(response);
JSONArray contestantObjects = jObject.getJSONArray("id");
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
But because it doesn't have "[]" I think it's not JSON object. therefore, I wrote another code based JSON array.
JSONArray contestantObjects = new JSONArray(response);
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
but result is same and Logcat shows:
Value {"id":{"timeSecond":1337861978,"time":1337861978000,"new":false,"machine":415106952,"inc":-2024241794},"body":"Not Available!","title":"Poland vs Greece","publishedDate":"2012-06-08 17:00:00 +0100","clazz":"SoccerMatchPreview","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595"} of type org.json.JSONObject cannot be converted to JSONArray
any suggestion would be appreciated. Thanks
JSONArray contestantObjects = jObject.getJSONArray("id");
Your error is here, id is itself a complex object, not an array.
"id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978}
Therefore, after getting the id JSON object, you should be able to get the individual attributes, e.g. inc, machine, new, time, and timeSecond.
JSONObject idObject = ...getJSONObject("id");
String machine = idObject.get("machine");
A JSON array data structure would have looked like this: [] signifies an array.
For example, "Animals":["Pig", "Cat", "Dog"].
In another example, it can also be an Array of complex objects, "Animals":[{"name":"AAA", "blood":"A"}, {"name":"BBB", "blood":"B"}].
EDIT: Here is a good JSON visualizer i would recommend.
http://jsonviewer.stack.hu/