开发者

JSON Creation from Java

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 开发者_JAVA技巧how to combine the 4 TEST objects with the text TESTMAIN. Any idea?


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!


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.


You need a JSONArray.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜