tags:

views:

14

answers:

3

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"  : "Santosh",    // Second Element
            "Marks" : 78,
            "age"   : 41
        }
   ]
}
A: 

You can use Google's gson

ozk
+1  A: 

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.

Amadan
A: 

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.

djna