2

Say I have a POJO as follows -

public class Pojo {

    String name;
    String address;
    Map<String, String> values;

    //getter/setters 
}

If, I convert it to a String in JSON format using Jackson, as follows -

    Pojo pojo= new Pojo ();
    pojo.setName("My Name");
    pojo.setAddress("Yet not found");

    Map<String, String> map = new HashMap<>();
    map.put("key1", "val1");
    map.put("key2", "val2");
    map.put("key3", "val3");

    pojo.setValues(map);

    ObjectMapper objectMapper = new ObjectMapper();
    String str = objectMapper.writeValueAsString(parentPojo);
    System.out.println(str);

I get a String in JSON format as follows -

{
    "name": "My Name",
    "address": "Yet not found",
    "values": {
        "key1": "val1",
        "key2": "val2",
        "key3": "val3"
    }
}

Is there any way, I can make it as follows, using Gson/Jackson?

{
    "name": "ParentName",
    "address": "Yet not found",
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
}

NOTE - I know it can be done easily, if I put everything inside a Single Map, But I Can NOT do that, I have some other business logic that depends on those.

CR Sardar
  • 921
  • 2
  • 17
  • 32

1 Answers1

2

With Jackson, annotate getValues() with @JsonAnyGetter and setValues() with @JsonAnySetter:

public class Pojo {

    private String name;
    private String address;
    private Map<String, String> values;

    // Getters and setters for name and address

    @JsonAnyGetter
    public Map<String, String> getValues() {
        return values;
    }

    @JsonAnySetter
    public void setValues(Map<String, String> values) {
        this.values = values;
    }
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359