jackson反序列化:我可以在to反序列化对象的字段中注入一个带有注解的值吗?

cwdobuhd  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(449)

我有这样一个对象要反序列化:

public class RelationsInput {

   Relation relation1;

   Relation relation2;

}

鉴于班级 Relation 看起来像这样:

public class Relation {

   RelationType relationtype;
   ... (more fields)

}
``` `RelationType` 是en enum,不是将反序列化的值,而所有其他值都是。
有没有可能,我可以“注入”字段的枚举值 `relationType` 在类的字段上有注解 `RelationInput` ? 如下所示

public class RelationsInput {

@RelationType(RelationType.OWNER)
Relation owner;

@RelationType(RelationType.TENANT)
Relation tenant;

}

Jackson提供这样的东西吗?
brjng4g3

brjng4g31#

恐怕没有这种事。如果您想使用类似的注解,可以使用自定义反序列化程序。首先创建如下内容:

@RequiredArgsConstructor
public abstract class RelationTypeDeserializer extends JsonDeserializer<Relation> {
    private final RelationType relationType;

    @Override
    public Relation deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        Relation r = p.readValueAs(Relation.class);
        r.setRelationtype(relationType);
        return r;
    }
}

然后实施实际操作:

public class OwnerDeserializer extends RelationTypeDeserializer {
    public OwnerDeserializer() {
        super(RelationType.OWNER);
    }   
}

public class TenantDeserializer extends RelationTypeDeserializer {
    public TenantDeserializer() {
        super(RelationType.TENANT);
    }
}

然后使用以下方法:

@Getter @Setter
public class RelationsInput {
    @JsonDeserialize(using = OwnerDeserializer.class)
    private Relation owner;
    @JsonDeserialize(using = TenantDeserializer.class)
    private Relation tenant;
}
wwtsj6pe

wwtsj6pe2#

您可以尝试使用 com.fasterxml.jackson.databind.deser.ContextualDeserializer 接口。它允许使用上下文创建反序列化程序示例。
参见以下示例:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class JsonContextualDeserializerApp {
    public static void main(String[] args) throws IOException {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = JsonMapper.builder().build();
        RelationsInput info = mapper.readValue(jsonFile, RelationsInput.class);

        System.out.println(info.toString());
    }
}

@Data
class RelationsInput {

    @JsonDeserialize(using = RelationStdDeserializer.class)
    @RelationTypeInfo(RelationType.OWNER)
    private Relation owner;

    @JsonDeserialize(using = RelationStdDeserializer.class)
    @RelationTypeInfo(RelationType.TENANT)
    private Relation tenant;

}

@Data
class Relation {

    private int id;
    private RelationType relationtype;
}

enum RelationType {OWNER, TENANT}

@Retention(RetentionPolicy.RUNTIME)
@interface RelationTypeInfo {
    RelationType value();
}

class RelationStdDeserializer extends StdDeserializer<Relation> implements ContextualDeserializer {

    private RelationType propertyRelationType;

    public RelationStdDeserializer() {
        this(null);
    }

    public RelationStdDeserializer(RelationType relationType) {
        super(Relation.class);
        this.propertyRelationType = relationType;
    }

    @Override
    public Relation deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonDeserializer<Object> deser = ctxt.findRootValueDeserializer(ctxt.getTypeFactory().constructType(Relation.class));
        Relation instance = (Relation) deser.deserialize(p, ctxt);
        if (this.propertyRelationType != null) {
            instance.setRelationtype(this.propertyRelationType);
        }
        return instance;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        RelationTypeInfo typeInfo = property.getMember().getAllAnnotations().get(RelationTypeInfo.class);

        return new RelationStdDeserializer(typeInfo.value());
    }
}

有效载荷的上述代码:

{
  "owner": {
    "id": 1
  },
  "tenant": {
    "id": 2
  }
}

印刷品:

RelationsInput(owner=Relation(id=1, relationtype=OWNER), tenant=Relation(id=2, relationtype=TENANT))

另请参见:
使用jackson反序列化为字符串或对象
如何将依赖注入自定义反序列化程序
jackson-将内部对象列表反序列化为一个更高级别的列表

yrefmtwq

yrefmtwq3#

如果按要求执行,relationtype字段的值将始终相同。无论如何,一个可行的解决方案是使用个性化序列化程序反序列化程序,如下所示:

public class RelationTypeJsonSerializer extends JsonSerializer<RelationType> {

    @Override
    public void serialize(RelationType value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String string = value.toString();//or something like that, convert the enum to string as you like
        gen.writeString(string);
    }
}

public class RelationTypeJsonDeserializer extends JsonDeserializer<RelationType> {

    @Override
    public RelationType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String toString = p.getCodec().readValue(p, String.class);//read the value as string
        return RelationType.build(toString);//convert back the value to object, use switch if needed)
    }
}

ObjectMapper om = new ObjectMapper();
SimpleModule localDateModule = new SimpleModule("RelationType Module");
localDateModule.addSerializer(RelationType.class, new RelationTypeJsonSerializer());
localDateModule.addDeserializer(RelationType.class, new RelationTypeJsonDeserializer());
om.registerModule(localDateModule);

为了前后转换枚举,我建议使用map<string,relationtype>,super simple和work perfect,如下所示:

Map<String, RelationType> map = new HashMap<String, RelationType>();
map.put("Some Type", RelationType.SOME_TYPE);
map.put("Some Other Type", RelationType.SOME_OTHER_TYPE);

使用get(字符串)进行序列化,使用get(值)进行反序列化(查找某个值的键)这是一个常规示例,当您要序列化没有默认序列化程序的对象时,请参阅此示例以获取更多信息如何使用jackson将color java类解析为json?

相关问题