JsonSerializable:从serialize方法调用标准序列化

时间:2014-02-25 15:20:07

标签: java json serialization fasterxml

问题出在serialize方法中(请参阅我的问题的代码部分)。一切顺利,直到我的ComplexGraph课程膨胀到二十三十个领域。当ComplexGraph成为真正的复杂图表时,通过jsonGenerator.writeNumberField("id", id)序列化每个字段非常难看。

问题: 如何在serialize方法中调用标准序列化?像:

public class ComplexGraph implements JsonSerializable {
    public void serialize(JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        if (isPrivate) return;
        //HERE IS THE QUESTION
        else jsonGenerator.standardSerialization(this);
    }
}

代码:

public class ComplexGraph implements JsonSerializable {

    private int id;
    private String text;
    private boolean isPrivate;

    // getters and setters

    @Override
    public void serialize(JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        if (isPrivate) return;
        jsonGenerator.writeStartObject();
        //IT'S VERY UGLY WHEN complexGraph HAS MANY DEPENDENCIES!
        jsonGenerator.writeNumberField("id", id);
        jsonGenerator.writeStringField("text", text);
        jsonGenerator.writeEndObject();
    }

    @Override
    public void serializeWithType(JsonGenerator jsonGenerator, SerializerProvider serializerProvider, TypeSerializer typeSerializer) throws IOException, JsonProcessingException {
        serialize(jsonGenerator, serializerProvider);
    }
}

0 个答案:

没有答案