猿问

将 pojo 序列化为嵌套的 JSON 字典

鉴于简单POJO:


public class SimplePojo {

    private String key ;

    private String value ;

    private int thing1 ;

    private boolean thing2;


    public String getKey() {

           return key;

    }

    ...

}


我没有问题序列化成这样的东西(使用Jackson):


 {

    "key": "theKey",

    "value": "theValue",

    "thing1": 123,

    "thing2": true

  }

但真正让我高兴的是,如果我可以这样序列化该对象:


 {

    "theKey" {

           "value": "theValue",

            "thing1": 123,

            "thing2": true

     }

  }

我在想我需要一个自定义序列化器,但我面临的挑战是插入一个新字典,例如:


@Override

public void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider provider) throws IOException {

    gen.writeStartObject();

    gen.writeNumberField(value.getKey(), << Here be a new object with the remaining three properties >> );



}

有什么建议么?


慕娘9325324
浏览 145回答 2
2回答

慕哥6287543

您不需要自定义序列化程序。您可以利用@JsonAnyGetter注释生成包含所需输出属性的地图。下面的代码采用上面的示例 pojo 并生成所需的 json 表示。首先,您已使用 注释所有 getter 方法,@JsonIgnore以便 jackson 在序列化期间忽略它们。将被调用的唯一方法是带@JsonAnyGetter注释的方法。public class SimplePojo {&nbsp; &nbsp; private String key ;&nbsp; &nbsp; private String value ;&nbsp; &nbsp; private int thing1 ;&nbsp; &nbsp; private boolean thing2;&nbsp; &nbsp; // tell jackson to ignore all getter methods (and public attributes as well)&nbsp; &nbsp; @JsonIgnore&nbsp; &nbsp; public String getKey() {&nbsp; &nbsp; &nbsp; &nbsp; return key;&nbsp; &nbsp; }&nbsp; &nbsp; // produce a map that contains the desired properties in desired hierarchy&nbsp;&nbsp; &nbsp; @JsonAnyGetter&nbsp; &nbsp; public Map<String, ?> getForJson() {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> map = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> attrMap = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; attrMap.put("value", value);&nbsp; &nbsp; &nbsp; &nbsp; attrMap.put("thing1", thing1);&nbsp; // will autobox into Integer&nbsp; &nbsp; &nbsp; &nbsp; attrMap.put("thing2", thing2);&nbsp; // will autobox into Boolean&nbsp; &nbsp; &nbsp; &nbsp; map.put(key, attrMap);&nbsp; &nbsp; &nbsp; &nbsp; return map;&nbsp; &nbsp; }}

慕码人2483693

您需要使用writeObjectFieldStart方法来写入字段并JSON Object以相同的类型打开新的:class SimplePojoJsonSerializer extends JsonSerializer<SimplePojo> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider serializers) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; gen.writeStartObject();&nbsp; &nbsp; &nbsp; &nbsp; gen.writeObjectFieldStart(value.getKey());&nbsp; &nbsp; &nbsp; &nbsp; gen.writeStringField("value", value.getValue());&nbsp; &nbsp; &nbsp; &nbsp; gen.writeNumberField("thing1", value.getThing1());&nbsp; &nbsp; &nbsp; &nbsp; gen.writeBooleanField("thing2", value.isThing2());&nbsp; &nbsp; &nbsp; &nbsp; gen.writeEndObject();&nbsp; &nbsp; &nbsp; &nbsp; gen.writeEndObject();&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答