0

I am using below code. and with getting this output.

output

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

CDD : {"CDDid" : 3456 }

But my required output like this below:

Header id 12345

Header value 123

Header Person 1

CDD CDDid 3456

import org.json.JSONException;
import org.json.JSONObject;

public class Test{

private static 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;
}
   public static void main(String[] args ){

   String json = " { \"Header\" : {\"id\" : 12345, \"value\" : \"123\", \"person\" : \"1\"} ,\"CDD\" : {\"CDDid\" : 3456 }}";
    try {
        HashMap<String, Object> map = getHashMapFromJson(json);
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
    } catch (JSONException e) {
        System.out.println("JsonTest" + "Failed parsing " + json + e);
    }
   }

   }
Venki WAR
  • 1,997
  • 4
  • 25
  • 38

2 Answers2

1

Here is my solution where I wanted to get it right already in the getHashMapFromJson method.

The toMap method is a simplified version from this answer, if your json is more complex you might want to look into implementing the full toMap method from that answer and the toListmethod as well.

private static 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();

        JSONObject value = jsonObject.getJSONObject(key);
        Map<String, Object> valueMap = toMap((JSONObject) value);
        valueMap.forEach((k,v) -> map.put(key + " " + k, v));
    }
    return map;
}

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = object.keys();
    while(keysItr.hasNext()) {
        String key = keysItr.next();
        Object value = object.get(key);

        map.put(key, value);
    }
    return map;
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0
String headerId = json.getJSONObject("Header").getString("id");

String headerValue = json.getJSONObject("Header").getString("value");

String headerperson = json.getJSONObject("Header").getString("person");

String CDDid = json.getJSONObject("CDD").getString("CDDid ");

This way to you retrieve json data

Venki WAR
  • 1,997
  • 4
  • 25
  • 38