【问题标题】:how to make a (récursive?) Custom Deserialization如何进行(递归?)自定义反序列化
【发布时间】:2019-10-19 03:57:18
【问题描述】:

我正在使用自定义反序列化,但我需要比我更好的大脑来解决这个问题。

为了简化: 我有一个 json 文件、一个实体、一个反序列化类和一个 main

关注EntityDeserialization(以实体为参数的searchEntitie函数)和Main(实体变量)

Entity.json (rootEntity是一个Entity对象)

[
  {
    "name": "BFA",
    "entityType": "secteur",
    "rootEntity": ""

  },
    {
    "name": "IT",
    "entityType": "service",
    "rootEntity": ""

  },
  {
    "name": "EX",
    "entityType": "offre",
    "rootEntity": "BFA"
  }
]

实体类

@JsonDeserialize(using = EntityDeserialization.class)
public class Entity {
    private String name;
    private String entityType;
    private Entity rootEntity;

实体反序列化

 public Entity deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException {
        JsonNode node = jp.getCodec().readTree(jp);
        String name =  node.get("name").asText();
        String entitype = node.get("entityType").asText();
        String rootEntity = node.get("rootEntity").asText();
        Entity entity = new Entity();
        entity = entity.searchEntity(entities, rootEntity);
        return new Entity(name, entitype,entity);
    }

主要

 public static void main(String[] args) throws FileNotFoundException {
        com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        TypeReference<List<User>> typeReferenceUser = new TypeReference<>() {};
        TypeReference<List<Entity>> typeReferenceEntity = new TypeReference<>() {};
        FileInputStream inputStreamUser = new FileInputStream("C:\\Users\\oraph\\Desktop\\user.json");
        FileInputStream inputStreamEntity = new FileInputStream("C:\\Users\\oraph\\Desktop\\entity.json");
        try {
           List<User> users = mapper.readValue(inputStreamUser,typeReferenceUser);
           List<Entity> entities = mapper.readValue(inputStreamEntity,typeReferenceEntity);
...

这里有问题: 我注意在 EntityDeserialization searchEntity(List entity, String rootEntity) 中使用我的函数,它是主要的并且正在填充过程中。

【问题讨论】:

    标签: java json object


    【解决方案1】:

    我找到了一种方法,连续两次反序列化。一是填写实体列表,二是使用该列表构建实体对象。

    【讨论】:

    • 更简洁的方法是使用 2 次解析。在第一次解析中构建实体对象并将它们存储在 的映射中。在第二个解析迭代所有实体是创建根和子实体之间的映射。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多