栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

多态对象的JSON使用者

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多态对象的JSON使用者

感谢Eric的评论,使我指向了程序员,我设法破解了它。这是我使用的代码(为了简化而简化)。

public static class Info {  @JsonProperty("Product")  public String product;  // Empty in the 0d version, One entry in the 1d version, two entries in the 2d version.  @JsonProperty("Dimensions")  public String[] dimensions;}public static class Info0d extends Info {}public static class Info1d extends Info {  @JsonProperty("Labels")  public String[] labels;}public static class Info2d extends Info {  @JsonProperty("Labels")  public String[][] labels;}public static class InfoDeserializer extends StdDeserializer<Info> {  public InfoDeserializer() {    super(Info.class);  }  @Override  public Info deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {    Class<? extends Info> variantInfoClass = null;    ObjectMapper mapper = (ObjectMapper) jp.getCodec();    ObjectNode root = (ObjectNode) mapper.readTree(jp);    // Inspect the `diemnsions` field to decide what to expect.    JsonNode dimensions = root.get("Dimensions");    if ( dimensions == null ) {      variantInfoClass = Info0d.class;    } else {      switch ( dimensions.size() ) {        case 1:          variantInfoClass = Info1d.class;          break;        case 2:          variantInfoClass = Info2d.class;          break;      }    }    if (variantInfoClass == null) {      return null;    }    return mapper.readValue(root, variantInfoClass);  }}

并将其安装在

ObjectMapper

// Register the special deserializer.InfoDeserializer deserializer = new InfoDeserializer();SimpleModule module = new SimpleModule("PolymorphicInfoDeserializerModule", new Version(1, 0, 0, null));module.addDeserializer(Info.class, deserializer);mapper.registerModule(module);factory = new JsonFactory(mapper);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449179.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号