简体   繁体   English

包含多个 json 值的响应是否总是必须包装在 java 中的数组中?

[英]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.我正在尝试使用 java 从后端返回响应,其中响应是 json 值的列表。

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我注意到 json 值总是返回包装在这样的数组中

[
{"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.我被要求返回 json 数据而不是在数组中,我在这样做时遇到了麻烦。 Is it even possible to return a list of json objects without being wrapped in an array?是否甚至可以返回 json 对象列表而不被包装在数组中? This is in java using the ObjectMapper class这是在 java 中使用 ObjectMapper class

List of json objects not wrapped in an array [] is a invalid json format and will give you error: multiple JSON root elements未包装在数组[]中的 json 对象列表是无效的 json 格式,并且会给您error: multiple JSON root elements

Possibly you can modify the result to this JSON format?可能您可以将结果修改为此 JSON 格式?

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

As others have pointed out, a list of objects without the wrapping array.would be invalid JSON.正如其他人指出的那样,没有包装数组的对象列表将是无效的 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 (eg substring) to remove the square braces, and then return that.但是,如果您真的必须返回它,您可以安排将 JSON 作为字符串,然后使用您选择的字符串方法(例如子字符串)删除方括号,然后返回。 Ultimately, a JSON is a String.最终,JSON一个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM