3

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.

3
  • You can format code easily by indenting with four spaces, that's all you need to do. Commented Sep 23, 2017 at 23:08
  • Could you please post the entire implementation of the Order class and its serialization/deserialization? Commented Sep 23, 2017 at 23:46
  • @SergeyBrunov it is a plan POJO object and i'm converting my class to JSON by using the below code.ObjectMapper mapperObj = new ObjectMapper(); String JSON = mapperObj.writeValueAsString(order); System.out.println(JSON); Commented Sep 24, 2017 at 10:27

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response. This helps.. Is there any annotations or some way I can tell Set<String> items to treat it as independent string object?
you can override the toString() method for your Order class by returning a string representation of your json object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.