JSON Structure for List of Objects

JavaJsonJaxb

Java Problem Overview


I would like to know, whats the right structure for a list of objects in JSON.

We are using JAXB to convert the POJO's to JSON.

Here is the choices, Please direct me what is right.

foos: [
             foo:{..},
             foo:{..}
      ]

or

   foos : [
           {...},
           {...}
          ]

If the first structure is right, what is the JAXB annotation I should use to get the structure right.

Java Solutions


Solution 1 - Java

The second is almost correct:

{
    "foos" : [{
        "prop1":"value1",
        "prop2":"value2"
    }, {
        "prop1":"value3", 
        "prop2":"value4"
    }]
}

Solution 2 - Java

The first example from your question,

> javascript > foos: [ > foo: { ... }, > foo: { ... } > ] >

is in invalid syntax. You cannot have object properties inside a plain array.

The second example from your question,

> javascript > foos: [ > { ... }, > { ... } > ] >

is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

Following is the correct one when you want to obey strict JSON:

"foos": [
    { ... },
    { ... }
]

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

Solution 3 - Java

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVanchinathan ChandrasekaranView Question on Stackoverflow
Solution 1 - JavaJustin NiessnerView Answer on Stackoverflow
Solution 2 - JavaBalusCView Answer on Stackoverflow
Solution 3 - JavaTimothy KanskiView Answer on Stackoverflow