如何根据json中的属性编写jackson反序列化器 [英] how to write jackson deserializer based on property in json

查看:205
本文介绍了如何根据json中的属性编写jackson反序列化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在类Type上编写json反序列化器,以便在根据名称从给定的json反序列化Type时,它会根据某些工厂方法将值(类型为接口Being)映射到其当前实现,该工厂方法根据名称返回正确的类名,并且没有任何明确的反序列化并且没有明确地使用new创建TigerBeing或HumanBeing的对象来填充剩余的类。

I want to write json deserializer on class Type so that when Type is deserialized from given json based on name it maps value (of type interface Being) to its current implementation based on some factory method that returns correct class name based on name, and populates remaining class without any explicit deserialization and without creating object of TigerBeing or HumanBeing explicitly using new.

我尝试使用@jsonCreator但是我必须初始化整个HumanBeing或TigerBeing使用new并在构造函数中传递所有json。我需要自动映射进一步用作进一步pojo的类型可能非常复杂。

I tried to use @jsonCreator but there i have to initialize entire HumanBeing or TigerBeing using new and passing all json in constructor. I need auto mapping for types further used as further pojo can be quite complex.

{type:[{
    "name": "Human",
    "value": { 
        "height":6,
        "weight":100,
        "languages":["spanish","english"]
    }
 },
{
"name":"Tiger",
"value":{
    "extinct":1,
    "found":["Asia", "America", "Europe", "Africa"]
}
}
]}

I have:

public class Type {
    String name;
    Being value;
}

public interface Being {
}

public class TigerBeing implements Being { 
    Integer extinct;
    String[] found;
}

public class HumanBeing implement Being {
    Integer height;
    Integer weight;
    String[] languages;
}


推荐答案

import java.io.IOException;

public class BeingDeserializer extends JsonDeserializer<Being> {

  @Override
  public Expertise deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonMappingException {

    JsonNode node = jp.getCodec().readTree(jp);
    String beingName = node.get("name").asText();
    JsonNode valueNode = node.get("value");
    BeingName beingByName = ExpertiseName.getBeingByName(beingName);
    if(beingByName ==null) {
      throw new JsonMappingException("Invalid Being " + beingName);
    }

    Being being =  JsonUtils.getObjectFromJsonNode(valueNode,
            ExpertiseFactory.getExpertise(beingByName).getClass());
    return being;
  }
}

通过这种方式,我能够解决上述问题。

In this way I was able to solve the above problem.

这篇关于如何根据json中的属性编写jackson反序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆