Skip to content
Advertisement

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

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

Advertisement

Answer

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.

Advertisement