Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string list/set to json objects in java

Tags:

java

json

jackson

I have a class named Order which contains one string list below

Set<String> items;

and when I convert this to 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.

like image 336
Naveen Avatar asked May 31 '26 12:05

Naveen


1 Answers

You can use some API, like Jackson, for creating JSON object and print it into string. First create a json ArrayNode for your items. Then for each string in your items, create an ObjectNode like this,

ObjectNode node = mapper.createObjectNode();
node.put("result", "xyz");

and add them to the ArrayNode. Finally you print the JSON object out.

like image 192
thegreatleaf Avatar answered Jun 03 '26 00:06

thegreatleaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!