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?

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

I use json-simple, which is as the name implies - simple :)
See section 2-3 of their examples. That covers how to use a List implementation to add an array.
any sample code to form the above JSON using the libraries.. Thanks
0

You need a JSONArray.

1 Comment

Nope, a JSONArray will create square brackets. He needs nested JSONObjects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.