1

This is my situation:

private Map<String, Object> data = new HashMap<>();

public void setName(String x) {put("name", x);}
public String getName() {return (String)get("name");}

public void setAge(Integer x) {put("age", x);}
public Integer getAge() {return (Integer)get("age");}

public void setUUID(UUID x) {put("uuid", x);}
public UUID getUUID() {return (UUID)get("uuid");}

Now when I generate JSON from this object I get {"data":{"name": ...}} I don't want the "data":{} part.

How to fix this?

[EDIT] When this class is exported as JSON by Spring the format is exactly what I want.

peterh
  • 11,875
  • 18
  • 85
  • 108
Ricardo
  • 335
  • 1
  • 4
  • 13

2 Answers2

0

Since your entire class seems to be inside a map, simply add a getter method for the Map to you class and instead of serializing the class itself, do it like:

gson.toJson(foo.getData())

On a side note, I gotta say it is pretty awkward having getters and setters doing actions on a map.

dambros
  • 4,252
  • 1
  • 23
  • 39
0

This works for me.

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(myClass);
Ricardo
  • 335
  • 1
  • 4
  • 13