Find value for key from dynamic json using java

I need to get key value from dynamic json.
Input-> json Object, String key
Output-> json (matches the key value)
Example

JsonObject Jmsg =

{
  "id": "1753_CORE1",
  "name": "Gtx cuda Service:1753",
  "shortName": "gt-service-1753",
  "createdDate": "Mar 31, 2015 4:47:10 PM",
  "config": {
    "oauthSecret": [
      {
        "id": 45,
        "config123": {
          "oauthSecret": "P8n2x5Hsst0nFRRB0A",
          "status": "CREATED"
        },
        "SERVER132": "1000"
      },
      {
        "id": 46,
        "config123": {
          "oauthSecret": "P8n2x5Htss0nFRRB0A"
        },
        "SERVER132": "1000"
      }
    ],
    "oauthKey": "154284-service-1753",
    "SERVER": "1000"
  },
  "features": [
    9004,
    9005
  ]
}

      

and String key = "status";
then JsonElement Jvalue = jsonGetValueformKey (Jmsg, key);
should return 'CREATED' in JsonElement or string type.

if String key = "features"; then
JsonElement Jvalue = jsonGetValueformKey (Jmsg, key);
should return [9004,9005] in JsonElement or jsonArray.

if the key is not found then return null
JsonObject Jmsg can be anything

+4


source to share


3 answers


try it



package json;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class MyApp {
    static List<String> list = new ArrayList<String>();
    public static void main(String[] args) {

        String key = "oauthSecret";

        String json2 = "{\"config\": {\"oauthSecret\": [{\"id\": 45,\"config123\": {\"oauthSecret\": \"P8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"},{\"id\": 46,\"config123\": {\"oauthSecret\": \"wP8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"}],\"oauthKey\": \"newtest\",\"SERVER\": \"1000\"},\"features\": [ 9004, 9005] ,\"d\":\"dd\"}";

        System.out.println("JSON: " + json2);
        JsonParser p = new JsonParser();
        check(key, p.parse(json2));
        System.out.println("list size: " + list.size());
        System.out.println(list);
    }



    private static void check(String key, JsonElement jsonElement) {

        if (jsonElement.isJsonArray()) {
            for (JsonElement jsonElement1 : jsonElement.getAsJsonArray()) {
                check(key, jsonElement1);
            }
        } else {
            if (jsonElement.isJsonObject()) {
                Set<Map.Entry<String, JsonElement>> entrySet = jsonElement
                        .getAsJsonObject().entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    String key1 = entry.getKey();
                    if (key1.equals(key)) {
                        list.add(entry.getValue().toString());
                    }
                    check(key, entry.getValue());
                }
            } else {
                if (jsonElement.toString().equals(key)) {
                    list.add(jsonElement.toString());
                }
            }
        }
    }

}

      

+8


source


This is a draft of a recursive approach to this.



Object find(JSONObject jObj, String k) throws JSONException {
    Iterator<?> keys = jObj.keys();

    while( keys.hasNext() ) {
        String key = (String)keys.next();
        if (key.equals(k)) {
            return jObj.get(key);
        }

        if ( jObj.get(key) instanceof JSONObject ) {
            return find((JSONObject)jObj.get(key), k);
        }

        if ( jObj.get(key) instanceof JSONArray ) {
            JSONArray jar = (JSONArray)jObj.get(key);
            for (int i = 0; i < jar.length(); i++) {
                JSONObject j = jar.getJSONObject(i);
                find(j, k);
            }
        }
    }

      

+5


source


You can use something like this: -

public Object checkKey(JSONObject object, String searchedKey) {
    boolean exists = object.containsKey(searchedKey);
    Object obj = null;
    if(exists){
        obj = object.get(searchedKey);
    }
    if(!exists) {      
         Set<String> keys = object.keySet();
         for(String key : keys){
             if ( object.get(key) instanceof JSONObject ) {
                 obj = checkKey((JSONObject)object.get(key), searchedKey);
            }
         }
    }
    return obj;
}

      

This will give you the object type for the key OR null if the key does not exist. You can change it and cast the return type Object

to whatever JSONObject

, String

or JSONArray

depending on your state, by checking its class with getClass()

.

Note. - This is only a link, but you can edit it according to your needs.

0


source







All Articles