Reputation: 427
I am Trying to parse nested JSON, But i don't know the format of JSON...I want all the Keys and Values of JSON.
Example:
{
"txnSpecificData1": "11",
"txnSpecificData2": "21",
"merchantData": {
"merchantSpecificData1": "111",
"merchantSpecificData2": "222",
"merchantSpecificData3": {
"data1": "1",
"data2": "2"
}
}
}
Now I want all Keys and their Values...I tried JSONParser but it is not giving all keys. Please some one guide me to do this.
I need value based on key.. Let's say If i give key as "merchantSpecificData2" it should return me value.
O/P should be MAP with all Key and Values:
OutPut Map : : : {txnSpecificData1=11, txnSpecificData1=22, merchantSpecificData1=111, merchantSpecificData2=222,data1=1,data2=2}
Upvotes: 3
Views: 8651
Reputation: 1445
A iterative solution to store all keys and respective value into a map. Note, all exception scenarios are not handled.
public static void main(String[] args) throws Exception{
JSONObject jo = new JSONObject(your_json_String_here);
Map<String, String> map = new HashMap<String, String>();
new Test().iterateJson(jo, map);
System.out.println(map);
}
public void iterateJson(JSONObject jo, Map map) {
for(Object o : jo.keySet()){
if(jo.get(o.toString()) instanceof JSONObject)
iterateJson(jo.getJSONObject(o.toString()), map);
else
map.put(o.toString(), jo.get(o.toString()));
}
}
Upvotes: 3
Reputation: 427
Here is the solution..
private static HashMap print(final JsonNode node) throws IOException {
HashMap map = new HashMap();
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = node.getFields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
final String key = field.getKey();
final JsonNode value = field.getValue();
if (value.isContainerNode()) {
print(value);
} else {
map.put(key, value);
}
}
return map;
}
Upvotes: 0
Reputation: 26067
Please refer this
Sample Code
public static void main(String[] args) throws JSONException {
String json = "{\"txnSpecificData1\": \"11\",\"txnSpecificData2\": \"21\",\"merchantData\": {\"merchantSpecificData1\": \"111\",\"merchantSpecificData2\": \"222\",\"merchantSpecificData3\": {\"data1\": \"1\",\"data2\": \"2\"}}}";
JSONObject jsonObject = new JSONObject(json);
JSONObject merchantData = (JSONObject) jsonObject.get("merchantData");
System.out.println(merchantData.get("merchantSpecificData2"));
}
Output
222
Upvotes: 2
Reputation: 8865
You can use http://json-lib.sourceforge.net/apidocs/net/sf/json/package-summary.html for parsing the JSON. Using JSONSerializer you can get a JSONObject parsing your string. Then methods available in JSONObject will give you all keys and values. Value can be simple like String/Long/Boolean or complex like another JSONObject/JSONArray.
Upvotes: 0