开发者

How to Create JSON Array

How to create something like this using jsp or java :

{
    "Maths" : [ 
        {
            "Name"  : "Amit",        // First element
            "Marks" : 67,
            "age"   : 23
        }, {
            "Name"  : "Sandeep",    // Second element
            "Marks" : 65,
            "age"   : 21
        }
    ], "Science" : [
        {
            "Name"  : "Shaili",     // First Element
            "Marks" : 56,
            "age"   : 27
        }, {
            "Name"  : "Sant开发者_运维技巧osh",    // Second Element
            "Marks" : 78,
            "age"   : 41
        }
   ]
}


First, indent all code by 4 spaces, otherwise it becomes illegible. Second, you probably can't generate meaningful comments (and why would you even want to?).

As for the code, it would be helpful to know the starting structure that you want to output. Without that, I can tell you of two approaches:

  1. Iterate on your structures, and print contents recursively

  2. Realise it's been already done, and look here. EDIT: Indeed, Gson is also good. Basically, google "java gson" and you'll have more answers than you can shake a stick at.


You can use Google's gson


JSON is just a text format, so you can just build a string

  "{" + subject.getName()   //etc

However it's way easier to use JAX/B to map from your Java objects to either JSON or XML. I have an article in my blog which describes some uses of JAX/B.


In JSP it's easy to make json array... here lest assume we have these name inside an arraylist: Banana, Grape, Orange.

So just put on this

[code] ArrayList res ---> assume this ArrayList containing Banana, Grape and Orange values.

String petik = "\'";

for(int count=0; count

that's all...! Now the output is gonna be this;

[code] ['Banana','Grape','Orange'] [/code]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜