[英]How to convert single String containing a comma separated json values into a single json object?
I am getting some data which is a single string我得到一些数据,它是一个字符串
"{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}"
how would I return that as a single json object like this using java libraries?我如何使用 java 库将其作为单个 json object 返回?
{{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}}
I have been trying to use the ObjectMapper class to read the value into a List but can't convert it.我一直在尝试使用 ObjectMapper class 将值读入列表但无法转换。
List<String> list = mapper.readValue(jsonString, new TypeReference<List<String>> () {});
I have the option to retrieve the data in an array like this:我可以选择像这样检索数组中的数据:
[{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}]
but I still can't manage to convert it to a single json Object response但我仍然无法将其转换为单个 json Object 响应
If you have a JSON string that looks as follows:如果您有如下所示的 JSON 字符串:
String userJson = "[{'name': 'Alex','id': 1}, "
+ "{'name': 'Brian','id':2}, "
+ "{'name': 'Charles','id': 3}]";
And a corresponding POJO that looks as follows:以及一个对应的 POJO,如下所示:
public class User
{
private long id;
private String name;
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
You could then use a library GSON to parse the JSON string into an array of User objects:然后,您可以使用库 GSON 将 JSON 字符串解析为用户对象数组:
Gson gson = new Gson();
User[] userArray = gson.fromJson(userJson, User[].class);
String jsonString = "{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}";
Object object = new ObjectMapper().readValue(jsonString, Object.class);
Try this尝试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.