【问题标题】:how to write jackson deserializer based on property in json如何根据json中的属性编写杰克逊反序列化器
【发布时间】:2016-02-17 11:50:25
【问题描述】:

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

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

{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;
}

【问题讨论】:

  • Jackson 支持多态类型 - 请参阅此处 programmerbruce.blogspot.de/2011/05/… - 示例 4 是这样的。你可以试试。此解决方案要求您的有效负载中至少具有类型属性,该属性将有效负载限定为TigerBeingHumanBeing

标签: java json jackson deserialization json-deserialization


【解决方案1】:
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;
  }
}

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

【讨论】:

  • 谢谢,试试这个。到现在为止一直在使用 hack。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 2017-12-09
  • 2016-10-23
  • 1970-01-01
  • 2014-12-18
相关资源
最近更新 更多