2

This is my JSONObject :

{
    "per_page": 3,
    "total": 12,
    "data": [{
            "color": "#98B2D1",
            "year": 2000,
            "name": "cerulean",
            "id": 1,
            "pantone_value": "15-4020"
        }, {
            "color": "#C74375",
            "year": 2001,
            "name": "fuchsia rose",
            "id": 2,
            "pantone_value": "17-2031"
        }
    ],
    "page": 1,
    "total_pages": 4
}

From this i should get all the keys including per_page,total,data,color,year,pantone_value,name,page and total_pages

If i use JSONObject.names() or JSONObject.keySet() . I only get the outermost keys

CannedMoose
  • 509
  • 1
  • 10
  • 18
Sunilkumar 3560
  • 81
  • 1
  • 1
  • 7

4 Answers4

2
package com.samples;

import java.util.Iterator;

import gvjava.org.json.JSONArray;
import gvjava.org.json.JSONException;
import gvjava.org.json.JSONObject;

public class JSONObjectSample {

    public static void main (String [] args) {
        String jsonString = new String("{\"per_page\": 3,\"total\": 12,\"data\": [{\"color\": \"#98B2D1\",\"year\": 2000,\"name\": \"cerulean\",\"id\": 1,\"pantone_value\": \"15-4020\" }, {\"color\": \"#C74375\",\"year\": 2001,\"name\": \"fuchsia rose\",\"id\": 2,\"pantone_value\": \"17-2031\" }], \"page\": 1,\"total_pages\": 4 }\r\n");
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            Iterator<String> keys = jsonObject.keys();
            while(keys.hasNext()) {
                String key = keys.next();
                System.out.println(key);
                if(jsonObject.get(key) instanceof JSONArray) {
                    JSONArray array = (JSONArray) jsonObject.get(key);
                    JSONObject object = (JSONObject) array.get(0);
                    Iterator<String> innerKeys = object.keys();
                    while(innerKeys.hasNext()) {
                        String innerKey = innerKeys.next();
                        System.out.println(innerKey);
                    }
                }
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
piy26
  • 1,574
  • 11
  • 21
  • This is just to solve the problem at hand. You need to write a recursive logic to get inside each inner JSONArray and JSONObjects to fetch their respective keys. – piy26 Apr 12 '18 at 06:35
  • 2
    I would suggest write a simple function with signature like public String[] getKeys(JSONObject jsonObject) and call it recursively whenever you encounter an value object of type JSONArray or JSONObject. – piy26 Apr 12 '18 at 06:37
1

You could use the google gson object parser. (This is not very pretty code but it gets the job done)

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.HashSet;
import java.util.Set;

public class GetKeys {
    public static void main(String[] args) {
        String jsonString = "{\"per_page\": 3,\"total\": 12,\"data\": [{\"color\": \"#98B2D1\",\"year\": 2000,\"name\": \"cerulean\",\"id\": 1,\"pantone_value\": \"15-4020\" }, {\"color\": \"#C74375\",\"year\": 2001,\"name\": \"fuchsia rose\",\"id\": 2,\"pantone_value\": \"17-2031\" }], \"page\": 1,\"total_pages\": 4 }\r\n";
        JsonParser parser = new JsonParser();
        JsonObject object = (JsonObject) parser.parse(jsonString);
        Set<String> keys = new HashSet<>();

        parseAllKeys(keys, object);

        keys.forEach(System.out::println);
    }

    private static void parseAllKeys(Set<String> keys, JsonObject object) {
        keys.addAll(object.keySet());
        object.entrySet().stream().filter(entry -> entry.getValue().isJsonObject()).forEach(entry -> parseAllKeys(keys, (JsonObject) entry.getValue()));
        object.entrySet().stream().filter(entry -> entry.getValue().isJsonArray()).forEach(entry -> entry.getValue().getAsJsonArray().forEach(subEntry -> parseAllKeys(keys, (JsonObject) subEntry)));
    }
}
tom
  • 2,735
  • 21
  • 35
  • { "RestResponse": { "result": [{ "area": "12541302SKM", "country": "IND", "capital": "Srinagar Jammu", "name": "Jammu and Kashmir", "id": 65, "largest_city": "Srinagar Jammu", "abbr": "JK" } ], "messages": [ "Total [36] records found." ] } } .when i tried with this json i'm getting com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject – Sunilkumar 3560 Apr 12 '18 at 07:17
  • Well, you have given a different json than in your question. Surely you adjust the code to make it more general. Nomatter what answer is given you are going to need to understand the code. – tom Apr 12 '18 at 07:19
  • @tom can you answer to https://stackoverflow.com/questions/60329223/how-to-update-existing-json-file-in-java/60329607#60329607? – Siva Feb 26 '20 at 16:57
1
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyClass
{
    public static ArrayList<String> keylist = new ArrayList<String>();
    public static void main(String args[]) throws JSONException
    {
        myfunction(myjson);
        System.out.println(keylist);
    }

    public static void myfunction(JSONObject x) throws JSONException
    {
        JSONArray keys =  x.names();
        for(int i=0;i<keys.length();i++)
        {
            String current_key = keys.get(i).toString();   
            if( x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
            {
                keylist.add(current_key);
                myfunction((JSONObject) x.get(current_key));
            } 
            else if( x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
            {
                for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
                {
                    if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
                    {
                        keylist.add(current_key);
                        myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j));
                    }
                }
            }
            else 
            {
                keylist.add(current_key);
            }
        }
    }
}

Possibilities:

  1. "key":"value"
  2. "key":{Object}
  3. "key":[Array]

Logic :

  1. If it contains just the value, I add the key to my list.
  2. If it is an object, I store the key and send the value recursively to the same function.
  3. If it is an array, I check whether it contains an object, if so I store the key and send the value recursively to the same function.
Natarajan
  • 21
  • 2
0

The below sample code will take a JsonObject and convert the Keys to lowercase. The two methods work in conjunction such that if there is any array in the request it will also convert these keys if needed and uses recursion.

public JsonArray parseArrayKeysToLower(JsonArray arrRequest) {
    JsonArray arrayTemp = new JsonArray();
    for(int i = 0; i < arrRequest.size(); i++) {
      if (arrRequest.getValue(i) instanceof JsonObject) {
        arrayTemp.add(parseObjectKeysToLower((JsonObject) arrRequest.getValue(i)));
      } else if (arrRequest.getValue(i) instanceof JsonArray) {
        arrayTemp.add(parseArrayKeysToLower((JsonArray) arrRequest.getValue(i)));
      } else {
        arrayTemp.add(arrRequest.getValue(i));
      }
    }
    return arrayTemp;
  }

  public JsonObject parseObjectKeysToLower(JsonObject request) {
    JsonObject requestToLower = new JsonObject();
    try {
      request.forEach(e -> {
        String key = e.getKey();
        if (e.getValue() instanceof JsonObject) {
          requestToLower.put(key.toLowerCase(), parseObjectKeysToLower((JsonObject) e.getValue()));
        } else if (e.getValue() instanceof JsonArray) {
          requestToLower.put(key.toLowerCase(), parseArrayKeysToLower((JsonArray) e.getValue()));
        } else {
          requestToLower.put(key.toLowerCase(), e.getValue());
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
    return requestToLower;
  }
Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
EliDev
  • 1