Home > Blockchain >  Add Duplicate Keys in JSON - Java
Add Duplicate Keys in JSON - Java

Time:09-25

{
    "student": [
        {
            "name": "TEST",
            "id": "1234",
            "@class" : "10"
        }
    ],
    "student": [
        {
            "name": "TEST12",
            "id": "1235",
            "@class" : "12"
        }
    ]
}

How to generate the JSON like this from classObj or any other way?

CodePudding user response:

The format you describe, with duplicated keys, is not a good one. As RFC 8259 says:

The names within an object SHOULD be unique.

As such, you're unlikely to find a library that makes it easy to generate this format, and you can't predict which student consumers would use.

It's reasonable to compose JSON as strings, if you're careful. The outer structure is simple. Generate it by concatenating hardcoded strings of JSON, then concatenate a generated String for each individual student object.

CodePudding user response:

This is considered an invalid JSON as per RFC-8259.

Instead you can group your students in an array

{
    "students": [
        {
            "name": "TEST",
            "id": "1234",
            "@class" : "10"
        },
        {
            "name": "TEST12",
            "id": "1235",
            "@class" : "12"
        }
    ]
}

  • Related