Procedure in Extracting JSON Array Elements - android

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");
}

Related

The best approach to store list in Firebase Firestore

I want to keep a list with the ID of the users who liked the specific object. To achieve that I created an array where I'm trying to keep that list.
I also want to display how many users like that object.
In mapper:
likes = getLikedListSize(it["userLikedOfferList"].toString())
then
private fun getLikedListSize(userList: String): String {
return userList.length.toString()
}
The problem is that function returns random numbers. For example in the array are two items, function return "8" etc.
What is a better approach to store list and get the size of it in Firestore?
When you are using the following method call:
getLikedListSize(it["userLikedOfferList"].toString())
It means that you are trying to pass to the getLikedListSize() method, the String representation of the array object. This representation is nothing else but the address of the object in the memory. This address it's a String that consists of 8 characters. That's the reason why, when you call .length you return the length of that String and not the actual length of the array. To solve this, simply pass the array, without converting it to a String:
getLikedListSize(it["userLikedOfferList"])
And change the method like this:
private fun getLikedListSize(userList: Array<String>): Int {
return userList.length
}
Now, when calling this method, you'll always get the number of elements that exist in the userLikedOfferList array.

How to read array data from the firestore using kotlin?

I am new in android development and when I read array data from firestore using following code
val variable = arrayOf(document.get("restaurant"))
and then loop over the variable using code
varibale.forEach {
Log.d("someTag", ${it.toString()} + " is your data")
}
I get the result with square brackets at log as following
[somedata, somedata2] is your data
my problem is that forEach loop runs only once and I am not able to get the result (without square brackets) as following
somedata is your data
somedata2 is your data
I have 2 elements in my restaurant array in firestore
I will be very thankfull to any one who will help me.
You are actually wrapping an array/list into another array when using arrayOf, that's why you see those brackets. Instead, try casting your document.get("restaurant") and then looping directly through it.
arrayOf doesn't parse an array. It creates a new array using the elements you pass to it. That's not what you want. You should instead cast document.get("restaurant") to the type that you expect to get from Firestore.
If a field is an array of strings, then the SDK will give you a List<*>, and you will need to make sure each item in the list is a String, if that's what you stored in the array.
val variable = document.get("restaurant") as List<*>
// Iterate variable here, make sure to check or convert items to strings

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.

What is the difference between optjson and getjson?

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

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.

Categories

Resources