What is the difference between optjson and getjson? - android

get(int index)
Get the object value associated with an index.
opt(int index)
Get the optional object value associated with an index.
What is the optional object or array ?

get(index) throws JSONException if the index isn't found where opt stand for optional and can be used for values that are optional in the JSONObject and there are good chances that it might not exist in some scenarios.
For ex. you have a JSONArray with 10 JSONObjects in it and 3 of your JSONObjects contains a value or index that might not exist in rest 7 JSONObject. In this scenario, instead of writing two different JSON parsers you can just simply use opt for the optional values and can use the same parser to parse all the JSONObjects in the array.
Hope it helps.

get throws a JSONException if the Object associated with "index" doesn't exist or is null.
opt returns null, instead.
so here "optional" means that that object or array may not exist
http://www.json.org/javadoc/org/json/JSONArray.html

Related

Creating json object without keys from array in android

Is there any way to create json object with only values and no keys, from array list in android?
I have array list like this
[12,name,description]
But i need to convert this to JSON Object like this
{"12","name","description"}
How to do this? Can anyone help?
No, you cannot create JSONObject without its key.
A modifiable set of name/value mappings. Names are unique, non-null
strings.
Source
Definition itself says names are unique, non-nullso you need to use key-value pair only, however it it possible to create JSONArray like this, but in that case also that JSONArray have some key.
"someKey":["a","b","c"]
So in this case also JSONArray needs to define under some key.

Why for each loop is not applicable for JSON array

When I was trying to parse a json array, the studio gave me a compilation error stating foreach is not applicable for json array.
Although I know how to get all objects and parse; I just wanted to know why foreach is not applicable even though the json array is an array
For each loop works like this -
For example for and Integer type ArrayList<Integer> list;
for (int x : list)
// process x here
But a JSONArray can have any type of value inside it.
For example -
[{"name" : John}, {"name" : Joe}, 1, false]
This is a valid JSONArray but it contains all kinds of objects namely - JSONObject, Integer, Boolean. So we would get a different type of value each time in for each loop.
So to apply a for each loop on this array we'll have to cast everything to Object class first -
for (Object o : myJsonArray)
Which doesn't makes much sense and would require a lot of useless effort.
Because JSONArrayclass doesn't implement Iterable interface.
Because JSONArray derives from Object and foreach expects the collection to be iterable.

public JSONObject (String json) in api19 scrambles order?

I was parsing a string to a JSONObject and noticed some weird behaviour. The orders of items get scrambled? Is this a bug or did i do something wrong?
Your 'items' are key/value pairs in a JSON object.
The order of key/value pairs within a JSON object is not guaranteed:
An object is an unordered set of name/value pairs.
If you need to preserve the order of those items you can put them in an array on the serializing side (probably a server):
An ordered list of values. In most languages, this is realized as an
array, vector, list, or sequence.
Official docs.

Iterating through JsonObject in Java/Android. NOT JsonArray

Here's my JSON data sample:
{
"node_1.1":{
"someCrap":{
"someCrap":"SomeValue"
}
},
"node_1.2":{
"Node_1.2.1":{
"Node_1.2.1.1":{
"param1":value,
"param2":value,
"param3":"value",
"paramThatIneed":{
"ThisIsWhatIActuallyNeed":"url",
"width":96,
"height":72
}
},
"Node_1.2.1.2":{
Same as above, just that paramThatINeed might be missing, gotta place imagePlaceHolder Here
},
//and so on... there are a total of 50 of these..
}
}
}
Now I could get the node_1.1 and Node 1.2 and the sub-node of it node_1.2.1
However, there are 50 sub-nodes inside of node_1.2.1, and they will have random names returned from the server. Its in string format but they're actually ints. Its a page ID.
Now I wanna iterate through the node_1.2.1 and get those sub-nodes and access their sub-nodes and take in the URL of the paramThatINeed. If the paramThatINeed is not present, I need to put some null/dummy value.
This is the code that I tried to work it as far as I've reached:
JSONObject jsonObj = new JSONObject(jsonStr); //jsonStr is the entire JSON string
JsonObject node_1.2= jsonObj.getJsonObject("node_1.1");
JsonObject node_1.2.1 = node_1.2.getJsonObject("node_1.2.1");
What do I do after this? Because I can only getJsonObject by passing a string param to it, I tried using the for loop but it doesn't take any int param.
Also, as I said before, the nodes after that have random names and not fixed. So I'm totally confused.
Please help me out if you know how to solve this problem. Please remember there's no JsonArray in this. I'm probably thinking of editing the JSON string itself and replacing some parts of the '{' with '[' and converting it to an array :( ... I think that's a sad approach.
Use this to iterate over an object.
Android (JSONObject) How can I loop through a flat JSON object to get each key and each value
but be careful, from json object you won't get the result in original order, like in json array. The result will be in alphabetical order (I hope I was clear). And you can use optJsonobject(), instead of getJsonObject(). It will returns null, instead of throw exception. You can use opt every where instead of get.

Procedure in Extracting JSON Array Elements

I have the following array response from a server to an android app.
[
{"1":
[{"name":"IEEE Meeting"},{"date":"2012-04-24 10:30:00"},{"Room":"ZACH102"},{"descr":"Final Meeting"},{"D":0.0057}]},
{"2":
[{"name":"Senior Design Demo"},{"date":"2012-04-24 16:30:00"},{"Room":"ZACH111A"},{"descr":"Demo"},{"D":0.019}]}
]
I perform a conversion to a JSONArray after receiving the response.
arr = new JSONArray(sb.toString());
How would I go about extracting the individual elements of name, date, room and so on?
So basically, its of this order
Array of objects 1, 2
- Each object 1, 2 has an array of different objects name, date, etc.
Convert the whole data in to a string.
Create a new JSONArray(string).
Loop over the array. (you'll get the count using length()).
Get the first object by using getJSONObject().
Get the array in the first object using getJSONArray.
Now using length() again you'll get the number of JSONObjects in it.
Loop over the num of objects and call get JSONObject() first followed by getString() or getDouble().
Repeat over the list of other objects and repeat step 4 - 7.
Have you checked out the documentation for JSONArray?
From the documentation, 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, String, or the JSONObject.NULL object.
A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.
The generic get() and opt() methods return an object which you can cast or query for type. There are also typed get and opt methods that do type checking and type coercion for you.
you can get all the parameters like this
JSONArray main_array = json.getJSONArray("array");
for(int i=0;i<main_array.length();i++) {
main_object = main_array.getJSONObject(i);
String name = main_object.getString("name");
String date = main_object.getString("date");
}

Categories

Resources