java - 如何反序列化杰克逊中嵌套的包装字符串?
问题描述
我有一个 JSON 字符串,其中包含一个嵌套和包装的 JSON 字符串。我想用杰克逊反序列化它,但我不确定如何。这是一个示例 bean:
@JsonIgnoreProperties(ignoreUnknown = true)
public class SomePerson {
public final String ssn;
public final String birthday;
public final Address address;
@JsonCreator
public SomePerson(
@JsonProperty("ssn") String ssn,
@JsonProperty("birthday") String birthday,
@JsonProperty("data") Address address,
@JsonProperty("related") List<String> related) {
this.ssn = ssn;
this.birthday = birthday;
this.address = address;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Address {
public final String city;
public final String country;
@JsonCreator
public Address(
@JsonProperty("city") String city,
@JsonProperty("country") String country) {
this.city = city;
this.country = country;
}
}
}
JSON 字符串类似于:
{
ssn: "001",
birthday: "01.01.2020",
address: "{ city: \"London\", country: \"UK\" }"
}
虽然我之前已经反序列化了 nsted 对象 - 当对象是一个包裹的字符串时,我对如何做到这一点相当迷茫。
解决方案
当内部对象被转义时JSON String
,我们需要“两次”反序列化它。第一次在反序列化 root 时运行JSON Object
,第二次我们需要手动运行。为此,我们需要实现实现com.fasterxml.jackson.databind.deser.ContextualDeserializer
接口的自定义反序列化器。它可能看起来像这样:
class FromStringJsonDeserializer<T> extends StdDeserializer<T> implements ContextualDeserializer {
/**
* Required by library to instantiate base instance
* */
public FromStringJsonDeserializer() {
super(Object.class);
}
public FromStringJsonDeserializer(JavaType type) {
super(type);
}
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
return ((ObjectMapper) p.getCodec()).readValue(value, _valueType);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
return new FromStringJsonDeserializer<>(property.getType());
}
}
我们需要用这个类注释我们的属性:
@JsonDeserialize(using = FromStringJsonDeserializer.class)
public final Address address;
从现在开始,您应该能够将上述JSON
有效负载反序列化到您的POJO
模型中。
也可以看看:
推荐阅读
- android - 如何在flutter中调用runApp方法中的两个类
- angular - Angular 2+,仅在条件适用但显示子元素时显示容器元素
- forms - Symfony 中的多种形式。显示有效,但多次持续存在
- vue.js - 如何在不停止执行测试的情况下等待一些文本?
- amazon-web-services - AWS Workspaces 和启用 RDP 的 EC2 实例有什么区别?
- c++ - 使用cmake错误链接boost日志
- java - 升级 Firebase 后 Android 未解决的依赖项
- algorithm - 在运行时在对象上的特定点捕捉两个对象
- jquery - 将所有克隆元素移动到容器
- sql - SQL查询到PowerShell中的变量