假设我有一个名为“ 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();
}
}
}