Home > Enterprise >  Does a response containing multiple json Values always have to be wrapped in an array in java?
Does a response containing multiple json Values always have to be wrapped in an array in java?

Time:12-15

I am trying to return a response from the back end using java where the response is a list of json values.

Is it possible to return the data in this format?

{"someKey": someValue},
{"someKey2": someValue},
{"someKey2": someValue}

I noticed that json values are always returned wrapped in an array like this

[
{"someKey": someValue},
{"someKey2": someValue},
{"someKey2": someValue}
]

I was asked to return the json data without being in an array and I am having trouble doing that. Is it even possible to return a list of json objects without being wrapped in an array? This is in java using the ObjectMapper class

CodePudding user response:

List of json objects not wrapped in an array [] is a invalid json format and will give you error: multiple JSON root elements

Possibly you can modify the result to this JSON format?

{
    "somekey": somevalue,
    "someKey2": someValue,
    "someKey3": someValue,
}

CodePudding user response:

As others have pointed out, a list of objects without the wrapping array.would be invalid JSON.

However, if you really must return that, you could arrange to get the JSON as a String, and then use String methods, of your choice (e.g. substring) to remove the square braces, and then return that. Ultimately, a JSON is a String.

  • Related