I have a json string which looks like: {"a":5, "b":"asd", "c":"{\\"d\\":3}"}
This can be deserialized to an object like:
class A {
int a; // --> 5
String b; // --> 'asd'
String c; // --> '{"d":3}'
}
but i want it to be deserialized as:
class A {
int a; // --> 5
String b; // --> 'asd'
MyClass c; // --> '{"d":3}'
}
where MyClass is:
class MyClass {
int d; // --> 3
}
How can I achieve this in jackson during deserialization?
I just found out that I can use the jackson converter:
public class MyClassConverter implements Converter<String, MyClass> {
@Override
public MyClass convert(String value) {
try {
return new ObjectMapper().readValue(value, MyClass.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public JavaType getInputType(TypeFactory typeFactory) {
return typeFactory.constructSimpleType(String.class, null);
}
@Override
public JavaType getOutputType(TypeFactory typeFactory) {
return typeFactory.constructSimpleType(MyClass.class, null);
}
}
And in the Bean:
class A {
int a;
String b;
@JsonDeserialize(converter = MyClassConverter.class)
MyClass c;
}
Try to do the deserialization twice:
A aObject = mapper.readValue(json,A.class);
aObject.setCObject(mapper.readValue(aObject.getC(),C.class));
class A {
int a;
String b;
String c;
C cObject;
}
class C {
int d;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.