【问题标题】:jackson serialize by type with mixing?杰克逊按类型序列化并混合?
【发布时间】:2017-11-05 11:20:34
【问题描述】:

我有一个像这样的 json 文件,需要由 Jackson 将其转换为 Java 用户实例。

"userid" : "1",
"myMixes" : [ {
     "data" : {
       "id" : 1,
       "ref": "my-Object-instance"
     },
     "type" : "object"
   }, {
     "data" : [ [ 0, 1], [ 1, 2 ] ],
     "type" : "list"
   }]

我的班级“用户”中有这个:

    // jackson should use this, if type="list"
    @JsonProperty("data")
    public List<List<Integer>> data_list = new ArrayList<>();

    // jackson should use this, if type="object"
    @JsonProperty("data")
    public Data data_object;

    @JsonProperty("id")
    public String id;

    // if type = "object", then jackson should convert json-data-property to Java-Data-Instance
// if type = "list",then jackson should convert json-data-property to List<List<Integer>> data
    @JsonProperty("type")
    public String type;

如果 json-type-property 的值称为“对象”,我如何告诉 jackson 生成 json-data-property 的 Data-Instance 并生成 List-Instance,如果 json-type- 的值-属性称为“列表”。

【问题讨论】:

    标签: java jackson jackson2


    【解决方案1】:

    我猜,我找到了最好的解决方案:

    @JsonCreator
        public MyMixes(Map<String,Object> props)
        {
            ...
    
            ObjectMapper mapper = new ObjectMapper();
    
            if(this.type.equals("object")){
    
                this.data_object = mapper.convertValue(props.get("data"), Data.class);
            }
            else{
                this.data = mapper.convertValue(props.get("data"), new TypeReference<List<List<Integer>>>() { });
            }
    
        } 
    

    如果有人有更短/更快的方法,请告诉我。

    【讨论】:

      【解决方案2】:

      您可以编写自己的反序列化器来检查接收到的 json 的 type 属性值。比如:

      @JsonDeserialize(using = UserDeserializer.class)
      public class UserData {
          ...
      }
      
      
      
      public class UserDeserializer extends StdDeserializer<Item> { 
      
      public UserDeserializer() { 
          this(null); 
      } 
      
      public UserDeserializer(Class<?> vc) { 
          super(vc); 
      }
      
      @Override
      public UserData deserialize(JsonParser jp, DeserializationContext ctxt) 
        throws IOException, JsonProcessingException {
          JsonNode node = jp.getCodec().readTree(jp);
          String type = node.get("type");
          if(type.equals("object")){
          // deserialize object
          }else if(type.equals("list")){
          // deserialize list
          }
          return new UserData(...);
         }
      }
      

      【讨论】:

      • 我的解决方案和你的有什么不同?你的更快吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多