-1

I have the following program which is building the JSON object. Not sure how to build array of arrays using following program.

pom.xml

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

JsonObjectConverter.java

public class JsonObjectConverter {

    private static final String STORE_ID = "TMSUS";

    public static void main(String[] args) {
        System.out.println(print1());
    }

    private static String print1() {
        JSONObject body = new JSONObject();

        JSONArray events1 = new JSONArray();
        events1.add(100L);
        events1.add(200L);
        JSONArray events2 = new JSONArray();
        events2.add(300L);
        events2.add(400L);

        JSONArray eventLogs = new JSONArray();
        eventLogs.add(events1);
        eventLogs.add(events2);

        body.put("storeId", STORE_ID);
        body.put("eventLogs", eventLogs);

        return body.toString();
    }

}

Output with the current program:

{
  "eventLogs": [
    [
      100,
      200
    ],
    [
      300,
      400
    ]
  ],
  "storeId": "TMSUS"
}

Expected Output:

{
  "eventLogs": [
    {
      "storeId": "TMSUS",
      "eventIds": [
        100,
        200
      ]
    },
    {
      "storeId": "TMSCA",
      "eventIds": [
        300,
        400
      ]
    }
  ],
  "userName": "meOnly"
}

Not sure how to get the expected output.

Please guide.

Nital
  • 5,784
  • 26
  • 103
  • 195
  • So you're inserting arrays of *arrays* and you're wondering why you're not getting arrays of *objects*? What is your question exactly? – shmosel Jul 27 '17 at 21:04
  • I am not sure how to build an array of arrays using the above program – Nital Jul 27 '17 at 21:07
  • You are building an array of arrays. But that's not the structure in your expect output. Clearly you have some concept of how to build JSON arrays and objects. You need to be more specific about where you're stuck. – shmosel Jul 27 '17 at 21:10

1 Answers1

0

Never mind, I got it working. Here is the updated method.

 private static String print1() {
        JSONObject body = new JSONObject();

        JSONObject eventLog1 = new JSONObject();
        JSONArray events1 = new JSONArray();
        events1.add(100L);
        events1.add(200L);
        eventLog1.put("storeId", "TMSUS");
        eventLog1.put("eventIds", events1);

        JSONObject eventLog2 = new JSONObject();
        JSONArray events2 = new JSONArray();
        events2.add(300L);
        events2.add(400L);
        eventLog2.put("storeId", "CBKUS");
        eventLog2.put("eventIds", events2);

        JSONArray eventLogs = new JSONArray();
        eventLogs.add(eventLog1);
        eventLogs.add(eventLog2);

        body.put("eventLogs", eventLogs);
        body.put("userName", "customer-portal-user");

        return body.toString();
    }
Nital
  • 5,784
  • 26
  • 103
  • 195