Jackson用多个设置相同值的静态工厂序列化了一个类

时间:2018-10-05 20:54:44

标签: java serialization jackson deserialization

假设我有一个名为“ SampleDto”的类,我想使用Jackson对其进行序列化和反序列化。现在,在下面的代码中,总是抛出RuntimeException。我如何在此类上进行序列化/反序列化?一些样本序列化/反序列化代码将不胜感激。

public class SampleDto {

    private static final String VALUE = "value";

    private final Object val;
    private final String someAttr;

    @JsonCreator
    private SampleDto(Object object, String attr) {
        this.val = object;
        this.someAttr = attr;
    }

    @JsonCreator
    public static SampleDto fromInt(int someInt) {
        return new SampleDto(someInt, "INT");
    }

    @JsonCreator
    public static SampleDto fromBool(boolean someBool ) {
        return new SampleDto(someBool, "BOOL");
    }

    public static SampleDto fromList(List<SampleDto> listOfSampleDto) {
        return new SampleDto(listOfSampleDto, "LIST"); 
    }

    @JsonProperty(BOOL_VAL)
    public boolean getBooleanVal() {
        if (this.someAttr != "BOOL") {
            throwEx("From BOOL");
        }
        return (Boolean) this.val;
    }

    @JsonProperty(INT_VAL)
    public int getIntegerVal() {
        if (this.someAttr != "INT") {
            throwEx("From INT");
        }
        return ((Number) this.val).intValue();
    }

    private static void throwEx(String type) {
        throw new RuntimeException(type);
    }

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        SampleDto sampleDto = SampleDto.fromBool(true);
        try {
            String valueAsString = objectMapper.writeValueAsString(sampleDto);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案