【问题标题】:How to deserialize a complex JSON如何反序列化复杂的 JSON
【发布时间】:2022-01-06 11:40:52
【问题描述】:

我是 Jackson 的新手,我需要反序列化 JSON,如下所示:

{
  "companies": [{
    "id": "some_id",
    "type": "sale",
    "name": "Company1",
    "attributes": {
      "countPeople": 300,
      "salary": 3000
    }
  }, 
  {
    "id": "new_id",
    "type": "IT",
    "name": "Company2",
    "attributes": {
      "countPeople": 100,
      "salary": 5000,
      "city": "New York",
      ...
    }
  }]
}

我想将其反序列化为 DTO,如下所示:

public class Companies {
    @JsonProperty("companies")
    public List<Company> companiesList;
}

public class Company {
    public String id;
    public String type;
    public String name;
    public Attributes attributes;
    
    @JsonCreator
    public Company(@JsonProperty("id") String id,
                   @JsonProperty("type") String type,
                   @JSonProperty("name") String name,
                   @JsonProperty("attributes") Attributes attributes
    ) {
        ...
    }
}

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        property = "type"
)
@JsonSubTypes({
        @JsonSubTypes.Type(name = "IT", value = ItAttributes.class)
        ...
})
public abstract Attributes {
    public int countPeople;
    ...
}

public class ItAttributes extends Attributes {
   ...
}

当我试图反序列化 JSON 时

public class Main {
    public static void main(String... args) {
        ObjectMapper mapper = new ObjectMapper();
        Companies comp = mapper.readValue(json, Companies.class);
    }
}

我遇到了一个异常:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class com.example.dto.Attributes]: missing type id property 'type' (for POJO property 'attributes')

显然Jackson 看不到type 属性,但我不明白为什么。
我该如何解决这个问题?

【问题讨论】:

    标签: java jackson jackson-databind


    【解决方案1】:

    您实际上需要在抽象Company 中使用@JsonTypeInfo@JsonSubTypes,如下所示:

    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            property = "type"
    )
    @JsonSubTypes({
            @JsonSubTypes.Type(name = "IT", value = ItCompany.class)
            ...
    })
    public abstract Company {
        public String id;
        public String type;
        public String name;
    }
    

    然后您将拥有具体的 Company 实现:

    public class ItCompany {
        public ItAttributes attributes;
    }
    
    // Other Company types
    

    您的Attributes 课程如下:

    public abstract Attributes {
        public int countPeople;
        ...
    }
    
    public class ItAttributes extends Attributes {
       ...
    }
    

    【讨论】:

    • 非常感谢!它也适用于我。
    • 不客气 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2015-08-07
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多