英文:
Deserialize json string to object with properties which are strings in jackson
问题
我有一个看起来像这样的 JSON 字符串:
```json
{"a":5, "b":"asd", "c":"{\"d\":3}"}
这可以被反序列化为一个对象,就像这样:
class A {
int a; // --> 5
String b; // --> 'asd'
String c; // --> '{\"d\":3}'
}
但我想要它被反序列化为:
class A {
int a; // --> 5
String b; // --> 'asd'
MyClass c; // --> '{\"d\":3}'
}
其中 MyClass 是:
class MyClass {
int d; // --> 3
}
在 jackson 中,我如何实现这个反序列化?
<details>
<summary>英文:</summary>
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?
</details>
# 答案1
**得分**: 2
我刚刚发现我可以使用Jackson转换器:
```java
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);
}
}
在Bean中:
class A {
int a;
String b;
@JsonDeserialize(converter = MyClassConverter.class)
MyClass c;
}
英文:
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;
}
答案2
得分: 0
尝试进行两次反序列化:
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;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论