猿问

使用在类字段中指定的自定义反序列化器反序列化字符串

我需要编写一个方法,它接受一些对象、fieldName给定对象的类中存在的一些字段名称和一些字段值value。该值是字段的 JSON 序列化形式。该方法应取值并相应地反序列化它,如下所示:


static void setField(Object obj, String fieldName, String value) throws Exception {

    Field field = obj.getClass().getDeclaredField(fieldName)

    Object valObj = objectMapper.readValue(value, field.getType());

    field.set(obj, valObj);

}

(我实际上只需要检索反序列化的值,而不是再次设置它,但这使它成为一个更好的例子。)只要 jackson 的默认反序列化就足够了。现在让我们假设我有一个带有自定义(反)序列化器的类:


class SomeDTO {

    String foo;

    @JsonSerialize(using = CustomInstantSerializer.class)

    @JsonDeserialize(using = CustomInstantDeserializer.class)

    Instant bar;

}

一种可能的解决方案是手动检查JsonDeserialize注释。但是,我真的不想尝试复制 Jackson 在决定使用哪种序列化器时遵循的任何策略,因为这看起来很脆弱(例如全局注册的序列化器)。


是否有使用 DTO 类中定义的字段反序列化配置反序列化值的好方法?也许在将字段的注释传递给 Jackson 的同时将值反序列化为字段的类型,以便他们得到尊重?


我设法获得了一个AnnotatedMember实例,其中包含所有必需的信息(JSON 注释和反射字段或 setter/getter 访问),但无法弄清楚我将如何使用它来反序列化一个独立的值由于缺乏文件:


final JavaType dtoType = objectMapper.getTypeFactory().constructType(SomeDTO.class);

final BeanDescription description = objectMapper.getDeserializationConfig().introspect(dtoType);

for (BeanPropertyDefinition propDef: beanDescription.findProperties()) {

    final AnnotatedMember mutator = propertyDefinition.getNonConstructorMutator();

    // now what? Also: How do I filter for the correct property?

}


米琪卡哇伊
浏览 191回答 2
2回答

繁花如伊

一种可能性是序列化对象,替换给定的字段,然后再次反序列化它。当序列化 from/toJsonNode而不是 JSON-String 时,这可以轻松完成,如下所示:static Object setField(Object obj, String fieldName, String value) throws Exception {    // note: produces a new object instead of modifying the existing one    JsonNode node = objectMapper.valueToTree(obj);    ((ObjectNode) node).put(fieldName, value);    return objectMapper.readValue(node.traverse(), obj.getClass());}但是,仅仅为了反序列化单个字段而对整个对象进行序列化和反序列化似乎开销很大,并且可能很脆弱,因为 DTO 类的其他方面会影响单个字段的反序列化过程

拉风的咖菲猫

import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.DeserializationContext;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializerProvider;import com.fasterxml.jackson.databind.annotation.JsonDeserialize;import com.fasterxml.jackson.databind.annotation.JsonSerialize;import com.fasterxml.jackson.databind.deser.std.StdDeserializer;import com.fasterxml.jackson.databind.ser.std.StdSerializer;import java.io.IOException;import java.util.Map;public final class Jackson {&nbsp; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()&nbsp; &nbsp; &nbsp; .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);&nbsp; public static void main(String[] args) throws IOException {&nbsp; &nbsp; Dto source = makeDto("Master", 31337);&nbsp; &nbsp; Dto dst = makeDto("Slave", 0xDEADBEEF);&nbsp; &nbsp; //1. read value of field "fieldName" from json source&nbsp; &nbsp; //2. clones destination object, sets up field "fieldName" and returns it&nbsp; &nbsp; //3. in case of no field either on "src" or "dst" - throws an exception&nbsp; &nbsp; Object result = restoreValue(dst, "details", OBJECT_MAPPER.writeValueAsString(source));&nbsp; &nbsp; System.out.println(result);&nbsp; }&nbsp; private static Object restoreValue(Object targetObject, String fieldName, String sourceObjectAsJson) throws IOException {&nbsp; &nbsp; String targetObjectAsJson = OBJECT_MAPPER.writeValueAsString(targetObject);&nbsp; &nbsp; Map sourceAsMap = OBJECT_MAPPER.readValue(sourceObjectAsJson, Map.class);&nbsp; &nbsp; Map targetAsMap = OBJECT_MAPPER.readValue(targetObjectAsJson, Map.class);&nbsp; &nbsp; targetAsMap.put(fieldName, sourceAsMap.get(fieldName));&nbsp; &nbsp; String updatedTargetAsJson = OBJECT_MAPPER.writeValueAsString(targetAsMap);&nbsp; &nbsp; return OBJECT_MAPPER.readValue(updatedTargetAsJson, targetObject.getClass());&nbsp; }&nbsp; private static Dto makeDto(String name, int magic) {&nbsp; &nbsp; Dto dto = new Dto();&nbsp; &nbsp; dto.setName(name);&nbsp; &nbsp; CustomDetails details = new CustomDetails();&nbsp; &nbsp; details.setMagic(magic);&nbsp; &nbsp; dto.setDetails(details);&nbsp; &nbsp; return dto;&nbsp; }&nbsp; private static final class Dto {&nbsp; &nbsp; private String name;&nbsp; &nbsp; @JsonSerialize(using = CustomDetails.CustomDetailsSerializer.class)&nbsp; &nbsp; @JsonDeserialize(using = CustomDetails.CustomDetailsDeserializer.class)&nbsp; &nbsp; private CustomDetails details;&nbsp; &nbsp; public String getName() {&nbsp; &nbsp; &nbsp; return name;&nbsp; &nbsp; }&nbsp; &nbsp; public void setName(String name) {&nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; }&nbsp; &nbsp; public CustomDetails getDetails() {&nbsp; &nbsp; &nbsp; return details;&nbsp; &nbsp; }&nbsp; &nbsp; public void setDetails(CustomDetails details) {&nbsp; &nbsp; &nbsp; this.details = details;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; return "Dto{" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name='" + name + '\'' +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ", details=" + details +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '}';&nbsp; &nbsp; }&nbsp; }&nbsp; private static final class CustomDetails {&nbsp; &nbsp; private int magic;&nbsp; &nbsp; public int getMagic() {&nbsp; &nbsp; &nbsp; return magic;&nbsp; &nbsp; }&nbsp; &nbsp; public void setMagic(int magic) {&nbsp; &nbsp; &nbsp; this.magic = magic;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; return "CustomDetails{" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "magic=" + magic +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '}';&nbsp; &nbsp; }&nbsp; &nbsp; public static final class CustomDetailsSerializer extends StdSerializer<CustomDetails> {&nbsp; &nbsp; &nbsp; public CustomDetailsSerializer() {&nbsp; &nbsp; &nbsp; &nbsp; this(null);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; public CustomDetailsSerializer(Class<CustomDetails> t) {&nbsp; &nbsp; &nbsp; &nbsp; super(t);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; public void serialize(CustomDetails details, JsonGenerator jg, SerializerProvider serializerProvider) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; jg.writeStartObject();&nbsp; &nbsp; &nbsp; &nbsp; jg.writeNumberField("_custom_property_magic", details.magic);&nbsp; &nbsp; &nbsp; &nbsp; jg.writeEndObject();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; private static final class CustomDetailsDeserializer extends StdDeserializer<CustomDetails> {&nbsp; &nbsp; &nbsp; public CustomDetailsDeserializer() {&nbsp; &nbsp; &nbsp; &nbsp; this(null);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; public CustomDetailsDeserializer(Class<CustomDetails> t) {&nbsp; &nbsp; &nbsp; &nbsp; super(t);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; public CustomDetails deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {&nbsp; &nbsp; &nbsp; &nbsp; JsonNode node = jp.getCodec().readTree(jp);&nbsp; &nbsp; &nbsp; &nbsp; int magic = (Integer) node.get("_custom_property_magic").numberValue();&nbsp; &nbsp; &nbsp; &nbsp; CustomDetails&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; customDetails = new CustomDetails();&nbsp; &nbsp; &nbsp; &nbsp; customDetails.setMagic(magic);&nbsp; &nbsp; &nbsp; &nbsp; return customDetails;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }}所以输出是:Dto{name='Slave', details=CustomDetails{magic=31337}}
随时随地看视频慕课网APP

相关分类

Java
我要回答