1

HI I am new to JSON and I have to create the below JSON from Java.

{{ "TESTMAIN" : { "TEST1" : { "384" : "250", "96" : "450" },
           "TEST2" :{ "384" : "5", "96" : "10" },
           "TEST3" : "256",
           "TEST4" : "T" }

I have created each object using JSONObject.put. But how to combine the 4 TEST objects with the text TESTMAIN. Any idea?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Vikram P
  • 85
  • 2
  • 11

3 Answers3

1

The json library is awfully verbose, this should do what you need:

final JSONObject wrapper = new JSONObject();
final JSONObject inner = new JSONObject();
final JSONObject innersub1 = new JSONObject();
innersub1.put("384", "250");
innersub1.put("96", "450");
final JSONObject innersub2 = new JSONObject();
innersub2.put("384", "5");
innersub2.put("96", "10");
inner.put("TEST1", innersub1);
inner.put("TEST2", innersub2);
inner.put("TEST3", "256");
inner.put("TEST4", "T");
wrapper.put("TESTMAIN", inner);
System.out.println(wrapper.toString());

I would advise you to look at more modern JSON libraries like Gson or Jackson, because they make life a lot simpler!

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

Is there any particular reason you're doing this by hand? There is a JSON library for Java that can do this for you.

JSON in Java, it has APIs for creating objects, arrays, etc. It will also serialize and deserialize JSON.

Dave G
  • 9,639
  • 36
  • 41
0

You need a JSONArray.

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215