0

I am trying to create a JSONArray but There is only one json object in array is coming DEMO2 why DEMO1 is not getting fetched?

 Map<String, Object> payload = objectMapper.convertValue(request.getPayload(), Map.class);
     
 JSONObject seg = new JSONObject();
 seg.put("s_code", "DEMO1");
 seg.put("v_type", "backend");
      
 JSONObject obj = new JSONObject();
 seg.put("s_code", "DEMO2");
 seg.put("v_type", "frontend");
      
 JSONArray segment = new JSONArray();
 segment.add(seg);
 segment.add(obj);
      
 payload.put("segments",segment);

There is only one json object in array DEMO2 why DEMO1 is not getting fetched? Edit:- Storing in jsonArray because need it that way I am extraction value like this

JSONArray segmentsList = payloadObject.getJSONArray("segments");

And output coming like this because of empty {} brackets my code is failing

 segments=[{v_type=frontend, s_code=LOC_DEMO_SEGMENT}, {}]
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
Destiel
  • 35
  • 6

1 Answers1

1

In your code, you are overriding value of seg. So at second place you need to put DEMO2 in obj, not seg. Check the updated code below.

Map<String, Object> payload = objectMapper.convertValue(request.getPayload(), Map.class);
     
JSONObject seg = new JSONObject();
seg.put("s_code", "DEMO1");
seg.put("v_type", "backend");
      
JSONObject obj = new JSONObject();
obj.put("s_code", "DEMO2"); // Here is the change
obj.put("v_type", "frontend"); // Here is the change
      
JSONArray segment = new JSONArray();
segment.add(seg);
segment.add(obj);
      
payload.put("segments",segment);
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47