Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json without knowning the keys

Tags:

java

json

android

i am trying to parse json in java without knowing the keys and the structure of json format and save that data into the hashmap

how would i cycle through the whole json format and store key and value into the hashmap

 {"id" : 12345, "value" : "123", "person" : "1"}

like in this example all the keys would be jsonobject none of them will be json array

There is some other library like jackson i don't want to use any third party library

like image 276
Nishant Tanwar Avatar asked Sep 05 '14 07:09

Nishant Tanwar


People also ask

Can JSON have value without key?

JSON doesn't have to have only key:value pairs; the specification allows to any value to be passed without a key. However, almost all of the JSON objects that you see will contain key:value pairs.

Can JSON be hacked?

JSON Hijacking is a kind of network security attack. In this attack, an attacker targets a system that has access to cross-domain-sensitive JSON data. This attack is similar to Cross-Site Request Forgery holding some differences.

Does JSON require key?

The two primary parts that make up JSON are keys and values. Together they make a key/value pair. Key: A key is always a string enclosed in quotation marks. Value: A value can be a string, number, boolean expression, array, or object.


2 Answers

This is Just an Example. For a JSON Like

{
 "status": "OK",
 "search_result": [

            {
                "product": "abc",
                "id": "1132",
                "question_mark": {
                    "141": {
                        "count": "141",
                        "more_description": "this is abc",
                        "seq": "2"
                    },
                    "8911": {
                        "count": "8911",
                        "more_desc": "this is cup",
                        "seq": "1"
                    }
                },
                "name": "some name",
                "description": "This is some product"
            },
            {
                "product": "XYZ",
                "id": "1129",
                "question_mark": {
                    "379": {
                        "count": "379",
                        "more_desc": "this is xyz",
                        "seq": "5"
                    },
                    "845": {
                        "count": "845",
                        "more_desc": "this is table",
                        "seq": "6"
                    },
                    "12383": {
                        "count": "12383",
                        "more_desc": "Jumbo",
                        "seq": "4"
                    },
                    "257258": {
                        "count": "257258",
                        "more_desc": "large",
                        "seq": "1"
                    }
                },
                "name": "some other name",
                "description": "this is some other product"
            }
       ]
}

Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

Roughly the code will look like:

// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();

while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();

    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

    // do something here with the value...
}

Try this Code Too

public void parse(String json)  {
   JsonFactory factory = new JsonFactory();

   ObjectMapper mapper = new ObjectMapper(factory);
   JsonNode rootNode = mapper.readTree(json);  

   Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
   while (fieldsIterator.hasNext()) {

       Map.Entry<String,JsonNode> field = fieldsIterator.next();
       System.out.println("Key:"field.getKey() + "\tValue:" + field.getValue());
   }

}

also give a look at this link

https://github.com/alibaba/fastjson

like image 194
Umer Kiani Avatar answered Sep 18 '22 20:09

Umer Kiani


Possible solution:

private HashMap<String, Object> getHashMapFromJson(String json) throws JSONException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    JSONObject jsonObject = new JSONObject(json);
    for (Iterator<String> it = jsonObject.keys(); it.hasNext();) {
        String key = it.next();
        map.put(key, jsonObject.get(key));
    }
    return map;
}

Testing with your example JSON string:

private void test() {
    String json = " {\"id\" : 12345, \"value\" : \"123\", \"person\" : \"1\"}";
    try {
        HashMap<String, Object> map = getHashMapFromJson(json);
        for (String key : map.keySet()) {
            Log.i("JsonTest", key + ": " + map.get(key));
        }
    } catch (JSONException e) {
        Log.e("JsonTest", "Failed parsing " + json, e);
    }

}

Output:

I/JsonTest(24833): id: 12345
I/JsonTest(24833): value: 123
I/JsonTest(24833): person: 1

Note: This is not ideal and I just wrote it real quick.

like image 42
Jared Rummler Avatar answered Sep 22 '22 20:09

Jared Rummler