杰克逊杰森到POJO的映射

时间:2017-04-07 09:27:47

标签: java json jackson json-serialization

我在与杰克逊创建地图时迷失方向。我的Json有以下结构

    {
  "d": {
    "__metadata": {
      "uri": "https://apisalesdemo8.successfactors.com:443/odata/v2/JobApplication(1463L)",
      "type": "SFOData.JobApplication"
    },
    "lastName": "K",
    "address": "123 Main Street",
    "cellPhone": "12345",
    "firstName": "Katrin",
    "city": "Anytown",
    "country": "United States",
    "custappattachment": {
      "results": [
        {
          "__metadata": {
            "uri": "https://apisalesdemo8.successfactors.com:443/odata/v2/Attachment(1188L)",
            "type": "SFOData.Attachment"
          },
          "fileExtension": "jpeg",
          "fileName": "hp-hero-img.jpeg",
          "fileContent": "/9j/4AA"
        },
        {
          "__metadata": {
            "uri": "https://apisalesdemo8.successfactors.com:443/odata/v2/Attachment(1189L)",
            "type": "SFOData.Attachment"
          },
          "fileExtension": "jpeg",
          "fileName": "hp-content-bkgd-img.jpeg",
          "fileContent": "/9j/4AAQSk"
        }]}}}

我确实找到了很多处理数组的教程,但是我已经失败了第一个令牌“d”。 并且根本不需要所有“__metadata”令牌。

我创建了一个包含lastName等属性和集合附件的pojo。 但我的代码总是在令牌“d”或“__metadata”

时失败
public class ResponseDataObject {


    private String lastName;
    private String address;
    private String cellPhone;
    private String firstName;
    private String city;
    private String country;
    private List<Attachment> attachments = new ArrayList<>();
    .....getters and setters

和杰克逊读者

    ObjectReader objectReader =
    mapper.readerFor(ResponseDataObject.class);
    ResponseDataObject dataObject = objectReader.readValue(file);

任何提示都将不胜感激。

此致 的Mathias

2 个答案:

答案 0 :(得分:1)

您可以使用@JsonIgnoreProperties注释来忽略与课程中定义的任何成员不匹配的属性,例如:

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseDataObject {

这将确保映射所有匹配的属性,并忽略其他属性。

答案 1 :(得分:0)

您需要忽略POJO中不存在的属性。在DeserializationFeature中为ObjectMapper设置以下属性:

// for version 1.x       
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// for newer versions
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 

反序列化代码:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
ResponseDataObject dataObject = mapper.readValue(file, ResponseDataObject.class);

并将此注释添加到ResponseDataObject类:

@JsonRootName(value = "d")
class ResponseDataObject {