I'm attempting to create a 1D String JSONArray and for reasons I cannot fathom It becomes 2D.
import org.json.*;
...
JSONArray ja = new JSONArray();
ja.put("minconf=1");
System.out.println(ja.toString());
JSONObject jo = new JSONObject();
jo.accumulate("method", "getbalance");
jo.accumulate("params", ja);
System.out.println(jo.toString());
This Outputs:
["minconf=1"]
{"method":"getbalance","params":[["minconf=1"]]}
I dont understand how/why the ["minconf=1"] becomes [["minconf=1"]] when added to the other JSONObject
Whoops.
The JSONObject.accumulate() method "Accumulates values under a key." Javadoc
Instead of using the .accumulate() method I should have used .put().
Adding an JSONArray via accumulate inserts it into an array straight away, however a single string value remains unmolested until the second string value is added.
jo.accumulate("method", "getbalance");
//Outputs: {"method":"getbalance"}
jo.accumulate("method", "getbalance");
jo.accumulate("method", "and");
//Outputs: {"method":["getbalance","and"]}
Related
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.
Can anyone explain me how to correctly insert a subobject into JSONObject? I've tried both implementations - org.json.simple and org.json and code like:
JSONObject obj = new JSONObject();
obj.put("key", "value");
obj.put("subobject", obj.toString());
After these strings I except:
{"key":"value","subobject":{"key":"value"}}
But actual value is:
{\"key\":\"value\","subobject":{"key":"value"}}
It always escapes the quotes while inserting JSONObject so I can't do it correctly. Of course I can try to modify the code but I wonder - really, nobody asked that before? So I guess the solution is right in front of me but I can't just see it. Help me please.
Simply put
JSONObject obj = new JSONObject();
JSONObject subobj = new JSONObject();
obj.put("key", "value");
obj.put("subobject", subobj);
without the toString()
Also, the way you print the JSONObject affects how it is displayed. Do you use System.out? or the debugger? As long as you can parse the result string again into a JSONObject, there is no real problem, right?
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/
Consider following piece of code:
JSONObject json = new JSONObject();
json.put("one", 1);
json.put("two", 2);
json.put("three", 3);
If i print the jsonobject it prints like this
{"three":"1","two":"2","one":"1"}
But i want like this.
{"one":"1","two":"2","three":"3"}
Please help. Thanks in advance.
The documentation at http://www.json.org/javadoc/org/json/JSONObject.html says:
A JSONObject is an unordered collection of name/value pairs.
In other words, properties of an object are accessed by name, not by position and the default serialized form does not guarantee any specific order.
Strict positioning comes only with arrays:
JSONArray json = new JSONArray();
json.put("1");
json.put("2");
json.put("3");
json.toString(); // results in ["1", "2", "3"]
The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key, produce the JSON string manually in what ever order necessary. Implementing a custom Comparator might help also.