Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find value for a key from a dynamic json using java

Tags:

java

json

search

I need to get the value of the key from a dynamic json.
Input-> json Object, String key
Output-> json element(corresponds to the value of the key)
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 type.

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

like image 858
Chinmay Samant Avatar asked Jul 01 '15 09:07

Chinmay Samant


People also ask

Can we get key from value in JSON?

Working with JSON String To get the key and value from a JSON string you can use the JSON. parse() method it will convert the JSON string to a JSON object and you can easily get key and value.

How do you check if a JSON object contains a key or not?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

How does JSON create key-value?

In order to set a key-value pair in a KiiObject, call the set() method of the KiiObject class. The set() method has an overloaded version for each data type. Specify a key-value pair as arguments of the set() method. The specified key-value pair will be saved at the first level of the JSON document hierarchy.


2 Answers

please try this

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

}
like image 185
Safwan Hijazi Avatar answered Sep 22 '22 10:09

Safwan Hijazi


This is a draft of a recursive approach for that.

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);
            }
        }
    }
like image 24
DrB Avatar answered Sep 22 '22 10:09

DrB