如何与杰克逊进行部分反序列化 [英] How to do a partial deserialization with Jackson
问题描述
在我的REST微服务中,我从另一个服务请求一个对象,该对象返回了一个巨大的嵌套JSON,例如:
In my REST microservice, I request an object from another service that returns me a huge nested JSON, for example:
{
"address": "19th Street",
"contact_info": {
"phones": {
"home": {
"first": {
"another_nested": 1234
}
}
}
}
}
我需要从另一个服务中获取此数据,仅在第一个字段中执行更改,然后通过HTTP发送.我要避免的是反序列化我这边的一切,并且必须在这里维护类.
有没有一种方法可以获取contact_info
的原始值,并只用Jackson来表示地址?像这样:
What I need to fetch this data from another service, perform a change only in the first field, and then send it via HTTP. What I'm trying to avoid is to deserialize everything on my side and having to maintain the classes here.
Is there a way to get the raw value of contact_info
and just have the representation of address with Jackson? Something like this:
public class FullAddress {
String address;
RawValue contactInfo;
}
推荐答案
最简单的方法是使用JsonNode
:
@Data
public class FullAddress {
private String address;
private JsonNode contactInfo;
}
或Map<String, Object>
:
@Data
public class FullAddress {
private String address;
private Map<String, Object> contactInfo;
}
它既可用于序列化也可用于反序列化.
It works for both serialization and deserialization.
但是,如果您想存储原始JSON,则可以定义一个自定义反序列化器:
If you, however, wants to store the raw JSON, then you could define a custom deserializer:
public class RawJsonDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode node = mapper.readTree(jp);
return mapper.writeValueAsString(node);
}
}
然后按如下所示使用它:
And then use use it as follows:
@Data
public class FullAddress {
private String address;
@JsonDeserialize(using = RawJsonDeserializer.class)
private String contactInfo;
}
但是,要进行序列化,可以使用@JsonRawValue
.
For serializing back, however, you can annotate the contactInfo
field with @JsonRawValue
.
这篇关于如何与杰克逊进行部分反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!