Reputation: 83
I want to fetch all the nodes of the below JSON object. For example
result, identification, payment etc.
{
"result": {
"identification": {
"transactionid": "Merchant Assigned ID",
"uniqueid": "d91ac8ff6e9945b8a125d6e725155fb6",
"shortid": "0000.0005.6238",
"customerid": "customerid 12345"
},
"payment": {
"amount": "2400",
"currency": "EUR",
"descriptor": "order number"
},
"level": 0,
"code": 0,
"method": "creditcard",
"type": "preauthorization",
"message": "approved",
"merchant": {
"key1": "Value1",
"key0": "Value0"
}
},
"id": 1,
"jsonrpc": "2.0"
}
I have used the following code:
JSONObject partsData = new JSONObject(returnString);
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String result=iterator.next();
System.out.println(result);
}
But the result I am getting is:
id
result
jsonrpc
How do I get all the node names?
Upvotes: 4
Views: 22023
Reputation: 426
Move your iterator logic (to iterate over json) in a method
e.g.,
public Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
if ( json.getJSONObject(key) instanceof JSONObject ) {
JSONObject value = json.getJSONObject(key);
parse(value,out);
}
else {
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
This way you can check for each sub node in the json object.
Upvotes: 1
Reputation: 1
You have to parse through all the objects.
JSONObject partsData = new JSONObject("result");
JsonObject identification = partsData.getJsonObject("identification");
JsonObject payment = partsData.getJsonobject("payment");
Upvotes: 0