[英]Convert a string list/set to json objects in java
I have a class named Order which contains one string list below 我有一个名为Order的类,下面包含一个字符串列表
Set<String> items;
and when I convert this to JSON: 当我将其转换为JSON时:
ObjectMapper mapperObj = new ObjectMapper();
String JSON = mapperObj.writeValueAsString(order);
System.out.println(JSON);
... I get output like below ...我得到如下输出
"items":[
"xyz",
"aaa"
]
I'm looking for an output something like below 我正在寻找类似下面的输出
"items":[
{
"result":"xyz"
},
{
"result":"aaa"
}
]
I don't want to create a class separately for a single string. 我不想为单个字符串单独创建一个类。
You can use some API, like Jackson, for creating JSON object and print it into string. 您可以使用某些API(例如Jackson)来创建JSON对象并将其打印为字符串。 First create a json
ArrayNode
for your items
. 首先为您的
items
创建一个JSON ArrayNode
。 Then for each string in your items
, create an ObjectNode
like this, 然后为
items
每个字符串创建一个这样的ObjectNode
,
ObjectNode node = mapper.createObjectNode();
node.put("result", "xyz");
and add them to the ArrayNode
. 并将它们添加到
ArrayNode
。 Finally you print the JSON object out. 最后,您将JSON对象打印出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.