jackson 要序列化为Map的ObjectMapper

b09cbbtk  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(185)

我有一个bean,它在内部使用一个map

class MyBean { 
    private Map<String,String> map;
    public MyBean(String key, String value) {
       map = Collections.singletonMap(key, value);
    }
}

我想将其序列化,使其使用底层Map作为表示{"akey":"avalue"}

...
ObjectMapper mapper = new ObjectMapper();
mapperWriteValueAsString(new MyBean("akey", "avalue"));

但默认的序列化返回map属性

{"map":{"akey":"avalue"}}

我设法创建了一个使用map属性的自定义序列化程序。这是实现它的唯一方法吗?

private static class MyBeanSerializer extends StdSerializer<MyBean> {

    public MyBeanSerializer() {
        this(null);
    }

    public MyBeanSerializer(Class<MyBean> t) {
        super(t);
    }

    @Override
    public void serialize(MyBean value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeObject(value.map);
    }
}
tvokkenx

tvokkenx1#

尝试@JsonUnwrapped注解:

class MyBean {
  @JsonUnwrapped
  private Map<String,String> map;
  public MyBean(String key, String value) {
     map = Collections.singletonMap(key, value);
  }
}

相关问题