0

I want to map an object to json to look like this:

 {"MyClass" : 
      [
        {"key" : "value"},
        {"key" : "value"}
      ]}

However my code is giving me:

{"MyClass" : {
      "list" : {
        "key" : "value",
        "key" : "value"
      }

And my code is like this:

public class MyClass {

    private List<Map<String,String>> list;

    //getters & setters......
  }

And:

Map<String, String> map1 = new HashMap<String,String>();
map1.put("key", "value");

Map<String,String> map2 = new HashMap<String,String>();
map2.put("key","value");

List<Map<String,String> list = new ArrayList<Map<String,String>();
list.add(map1);
list.add(map2);

And I am using ObjectMapper to map the values. What can I do to get the layout I want?

3
  • the code seems to work, what's the problem? the names don't match? Commented Apr 12, 2018 at 15:15
  • it works but not the same format I want. For example, I don't want the name of the list printed Commented Apr 12, 2018 at 15:18
  • this is the name of the variable, you can change it to different name or use @JsonProperty notation as my example below Commented Apr 12, 2018 at 15:25

1 Answer 1

1

using your code

class MyClass  {

    @JsonProperty("MyClass")
    public List<Map<String,String>> list;

    public static void main(String[] args) throws JsonProcessingException {
        Map<String, String> map1 = new HashMap<String,String>();
        map1.put("key", "value");

        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("key","value");

        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        list.add(map1);
        list.add(map2);

        MyClass d = new MyClass();
        d.list = list;

        ObjectMapper objectMapper = new ObjectMapper();

        String json = objectMapper.writeValueAsString(d);
        System.out.println(json);
    }
}

output

{"MyClass":[{"key":"value"},{"key":"value"}]}

I used @JsonProperty to change the name but you can also change the name of the var from list to whatever

Note: this is just draft implementation... don't use public class vars, and such...

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

2 Comments

I'm not getting that layout on mine, I'm using prettyprinter to print, could that make a difference?
@user3871995 pretty print effect only the display format not the structure, what do you get when running my example code?

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.