How to get all the nodes and child nodes of a JSON object in java?

I want to get all the nodes below the 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 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 I get the result:

id
result
jsonrpc

      

How do I get all node names?

+3


source to share


2 answers


Move your iterator logic (to iterate over json) in a method like

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 every sub node in the json object.

+1


source


You need to disassemble all objects.



JSONObject partsData = new JSONObject("result"); 

JsonObject identification = partsData.getJsonObject("identification");

JsonObject payment = partsData.getJsonobject("payment");

      

0


source







All Articles