Gson、Jackson、Flaten Map/HashMap

Gson, Jackson, Flaten Map/HashMap

假设我有一个 POJO 如下 -

public class Pojo {

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

    //getter/setters 
}

如果,我用Jackson转成JSON格式的String,如下-

    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);

我得到 JSON 格式的 String 如下 -

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

有什么办法,我可以用Gson/Jackson?

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

注意 - 我知道这很容易完成,如果我把所有东西都放在一个单一的 Map 中,但我不能那样做,我有一些其他的业务逻辑依赖于那些.

与 Jackson 一起,用 @JsonAnyGetter and setValues() with @JsonAnySetter 注释 getValues():

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;
    }
}