Android: Dynamically Get JSON Array Key Name From JSON - java

I have a json link, if we open it I get a following result
{
"Status": "Success",
"All_Details": [{
"Types": "0",
"TotalPoints": "0",
"ExpiringToday": 0
}],
"First": [{
"id": "0",
"ImagePath": "http://first.example.png"
}],
"Second": [{
"id": "2",
"ImagePath": "http://second.example.png"
}],
"Third": [{
"id": "3",
"ImagePath": "http://third.example.png"
}],
}
What I need is, I want to dynamically get all the key names like status, All_details, First etc.
And I also want to get the data inside the All_details and First Array.
I used following method
#Override
public void onResponse(JSONObject response) throws JSONException {
VolleyLog.d(TAG, "Home Central OnResponse: " + response);
String statusStr = response.getString("Status");
Log.d(TAG, "Status: " + statusStr);
if (statusStr.equalsIgnoreCase("Success")) {
Iterator iterator = response.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
}
}
}
I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???

First, to get the keynames, you can easily iterate through the JSONObject itself as mentioned here:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Then, to get the values of the array:
JSONArray arr = response.getJSONArray(key);
JSONObject element;
for(int i = 0; i < arr.length(); i++){
element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details)
}

If you want to get the JSON array from the response JSONObject you can use the JSONArray class. JSONObject has a method to get a JSONArray: getJSONArray(String). Remember to catch the JSONException when trying this. This exception will be thrown if there is no key for example.
Your code could look like this (only the while loop):
while (iterator.hasNext()) {
String key = (String)iterator.next();
try {
JSONArray array = response.getJSONArray(key);
// do some stuff with the array content
} catch(JSONException e) {
// handle the exception.
}
}
You can get the values from the array with the methods of JSONArray (see the documentation)

Something like this will allow you to iterate on array and individual fields once you have extracted the keys using what you have done. Instead of "Types" use the key variable you will create before this.
JSONArray allDetails = response.getJsonArray("All_Details")
for (int i = 0 ; i < allDetails.length(); i++) {
JSONObject allDetail = allDetails.getJSONObject(i);
allDetails.getString("Types");
}

First of all I want to inform you that it's not a valid JSON. Remove the last Comma (,) to make it valid.
Then you can Iterate like here
JSONArray myKeys = response.names();

Try this one
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
try {
String dynamicKey = (String) keys.next();//Your dynamic key
JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

Trying to explain a a java for loop which requests JSON objects and requests for Queues

I'm trying to do a written report on some code and I found one on Youtube. However, I don't understand how some of this loop works. I understand that it goes through every item in the list and fetches each value for each variable and that it then adds all values to a list which is presented in an XML view in Android studio. if someone could breakdown what is happening it would be greatly appreciated!
private void setupData() {
RequestQueue queue = Volley.newRequestQueue(this);
String url =" - hidden - ";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length() ; i++){
JSONObject jo = jsonArray.getJSONObject(i);
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating"));
supplierList.add(supplier);
System.out.println(jsonArray.length());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
System.out.println("That didn't work!");
}
});
queue.add(request);
}
Though you can simply read about the JSONObject class and all other classes belonging to the package. But, let me put it what I understand with an example here.
Here is the response json that is being received.
{
"data": [
{
"id": 1,
"name": "ABCD",
"url": "https://www.stackoverflow.com",
"specialization": "master",
"country": "India",
"rating" : 5
},
{
"id": 1,
"name": "ABCD",
"url": "https://www.stackoverflow.com",
"specialization": "master",
"country": "India",
"rating" : 5
}]
}
The code is trying to process this complete json.
It starts with reading the "data" object into an array since it represents an array and then convert every object block in that array to a Supplier model class and then add it into SupplierList.
JSONArray jsonArray = response.getJSONArray("data"); // reads the "data" attribute.
for (int i = 0; i < jsonArray.length() ; i++){ // Iterates every block, every block inside this array represent a JSONObject
JSONObject jo = jsonArray.getJSONObject(i); // Reads every block using simple loop and index logic
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating")); // Reads the attributes from the JSONObject to create an instance of Supplier class
supplierList.add(supplier); // Adds the supplier instance to the list
System.out.println(jsonArray.length());
}

How to select the complete JSON node if any key-value pair matched inside the node?

I have JSON some thing like below
{
"title": "seller_information",
"sellers": [
{
"seller": "s1",
"prod_on_sale": "flowers"
},
{
"seller": "s2",
"prod_on_sale": "pet_food"
},
{
"seller": "s3",
"prod_on_sale": "vegatables"
}
]
}
I am aware how to iterate through JSON Array based on key and extract the values of that particular key. But stuck with one scenario let say instead of key i have value with if i have value 's1' with me i want to traverse through above JSON and if it matches with any value i want to extract the complete JSON related to that value 's1' like below
{
"seller": "s1",
"prod_on_sale": "flowers"
}
Please suggest some idea how can i do this i am newbie to JSON. Thanks in advance.
public static JSONObject getObject(String itemToSearch, JSONArray array) {
for(int i = 0; i < array.length(); i++) {
try {
JSONObject jsonObject = array.getJSONObject(i);
if (jsonObject.getString("seller").equals(itemToSearch)){
return jsonObject;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
you can use this function by sending array of sellers from your JSON
sellersArray = yourJSON.getJSONArray("sellers");

Is there a way to name each JSONObject in an array?

{
"Object1": {
"description": "An object",
"data": "more data"
},
"Object2": {
"description": "An object",
"data": "more data"
}
}
How would I use GSON to iterate over the elements in this JSON Object to easily parse each element one by one?
Yes there is, but PrabhakarP is right, associative arrays in JSON are objects. So in your case,
{
"Object1": {
"description": "An object",
"data": "more data"
}
}
You would have a meta-object containing each array element as a property, which doesn't really make sense. You should parse it differently.
But if you still need, in GSON, then try ,
JsonArray body = gson.fromJson(yourString, JsonArray.class);
JSONObject metaObj = new JSONObject();
for (JsonElement currEle : paymentsArray) {
JSONObject currObj = currEle.getAsJsonObject();
String nameVal = currObj.get("name");
currObj.remove("name");
metaObj.addProperty(nameVal, currObj);
}
I would suggest you to add a property to each object in array and use it
I looked at the man page and found I could loop over the set of members in the object.
JsonObject obj = gson.fromJson(jsonFile, JsonObject.class);
for(Map.Entry<String, JsonElement> element : obj.entrySet()) {
Object obj = gson.fromJson(element.getValue(), Object.class);
// do stuff with the object
}

How to access JSON data with multiple array objects : android

I am stuck in getting the data from the JSON file with multiple data sets.
{
"status": "ok",
"count": 3,
"count_total": 661,
"pages": 133,
"posts": [
{
"id": 20038,
"type": "post",
"slug": "xperia-launcher-download",
"url": "http:\/\/missingtricks.net\/xperia-launcher-download\/",
"status": "publish",
"title": "Download Xperia Launcher app for Android (Latest Version)"
},
{
"id": 94,
"type": "post",
"slug": "top-free-calling-apps-of-2014-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2014-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android November 2014"
},
{
"id": 98,
"type": "post",
"slug": "top-free-calling-apps-of-2016-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2016-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android December 2016"
}
]
}
I need to access the title, url and status from the above JSON file.
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
} catch (JSONException e) {
Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
I am getting a JSONException with the above code.
What should I do to access the title,status and url from the JSON File?
You have to fetch your JSONArray which is inside a JSONObject , so create a JSONObject and fetch your array with index "posts"
1.) result is a JSONObject so create a JSONObject
2.) Fetch your JSONArray with index value as "posts"
3.) Now simply traverse array objects by fetching it through index
JSONObject jObj = new JSONObject(result);
JSONArray jArray = jObj.getJSONArray("posts");
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
Note : i don't know weather it is a sample response with shorter version though your json object should ends with } not with , .
[{"id":20038,"type":"post","slug":"xperia-launcher-download","url":"http://missingtricks.net/xperia-launcher-download/","status":"publish","title":"Download
Xperia Launcher app for Android (Latest Version)",
// ^^^ there should be a } not a , to end json
// so make sure to do the correction so it will look like => ...st Version)"},
{"id":94,"type":"post","slug":"top-free-calling-apps-of-2014-year","url":"http://missingtricks.net/top-free-calling-apps-of-2014-year/","status":"publish","title":"Best
Free Calling Apps for Android November 2014", ]
Improvements :
you can use optString to avoid null or non-string value if there is no mapping key
This has two variations
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
fishData.status = json_data.optString("status","N/A");
// will return "N/A" if no key found
or To get empty string if no key found then simply use
fishData.status = json_data.optString("status");
// will return "" if no key found where "" is an empty string
You can validate your JSON here.
If entire JSON getJsonObject() is not working, then you should parse JSON objects & array in multiple arrays then use them.

JSON Parsing Nested Array Objects

Using Simple-JSON on the following JSON formatted file, I'm having a lot of trouble understanding how to access the objects within the array under "name".
JSON File:
[
{
"name":{
"firstName": "Developer",
"lastName": "D"
},
"id": 00,
"permissionLevel": 3,
"password": 12345
},
{
"name":{
"firstName": "Bob",
"lastName": "Smith"
},
"id": 01,
"permissionLevel": 2,
"password": 23456
}
]
I'm able to obtain the information for all of the other contents because they're not located in a nested array; However, when I attempt to retrieve the objects under "name", all that is output is the String found in the JSON file.
Current code:
String[] searchData = {
"name",
"firstName",
"lastName",
"id",
"permissionLevel",
"password"
};
jsonArray = (JSONArray)new JSONParser().parse(s);
for(int i = 0; i < jsonArray.size(); i++){
JSONObject jo = (JSONObject)jsonArray.get(i);
for(int j = 0; j < searchData.length; j++){
System.out.println(
searchData[j] + ": " + jo.get(searchData[j]));
}
}
Output:
name: [{"firstName":"Developer","lastName":"D"}]
firstName: null
lastName: null
id: 0
permissionLevel: 3
password: 12345
name: [{"firstName":"Bob","lastName":"Smith"}]
firstName: null
lastName: null
id: 1
permissionLevel: 2
password: 23456
As you can see, "name" outputs a String from the JSON file, and not each individual value.
In the end, I need to write a universal code that can accept new "searchData" tags for each file that's input.
Might someone be able to direct me how to obtain objects held
within nested arrays?
Or perhaps I need to use a different Library? If so, which one is the most efficient for Java? I'm not programming for Android, and I continue to find Library suggestions for Android, constantly.
My apologies if this post is a dupe, but no other posts are aiding me.
You should get your firstname and lastname, like:
jo.get("name").get("firstname");
jo.get("name").get("lastname");
To get the objects held within nested arrays/objects, you will have to write a recursive method and flatten the structure into a map. Below example shows the same:
public static void main(String args[]) throws ParseException {
Object object = new JSONParser().parse("[ { \"name\":{ \"firstName\": \"Developer\", \"lastName\": \"D\" }, \"id\": 00, \"permissionLevel\": 3, \"password\": 12345 }, { \"name\":{ \"firstName\": \"Bob\", \"lastName\": \"Smith\" }, \"id\":01, \"permissionLevel\": 2, \"password\": 23456 }]");
Map<String, Object> pairs = new HashMap<>();
addValues(object, pairs);
System.out.println(pairs);
}
public static void addValues(Object object, Map<String, Object> pairs){
if(object instanceof JSONObject){
JSONObject jsonObject = (JSONObject) object;
for(String key : jsonObject.keySet()){
if(jsonObject.get(key) instanceof JSONObject || jsonObject.get(key) instanceof JSONArray){
addValues(jsonObject.get(key), pairs);
}else{
pairs.put(key, jsonObject.get(key));
}
}
}else if(object instanceof JSONArray){
JSONArray jsonArray = (JSONArray)object;
for(Object element : jsonArray){
addValues(element, pairs);
}
}
}
You can tweak this method to have keys like name.firstname or name.lastname depending on requirements.
I understand that you want the searchData tags to be taken into consideration while parsing the JSON. I would suggest using Google Gson for this case.
You can write a POJO which return the ArrayList<User> for your JSON.
Refer this article on how use Google Gson

Categories