当json键与jackson相同时解析json

时间:2015-03-27 19:26:20

标签: java android json jackson

我的json具有相同的键,如此处所示

{
  "tests": [
    {
      "id": 1,
      "object_type": "bla",
      "objects": {
        "id": 59,
        "company_name": "apple",
        "project_name": "iphone",
        "duration": 145
      }
    },
    {
      "id": 66,
      "object_type": "gla",
      "objects": {
        "id": 59,
        "institution_name": "Test",
        "subject": "Gsks",
        "duration": 2
      }
    }
  ]
}

当我创建课程时

的A.class 列出myClass;

TestClass.class

int id;
String object type;
@JsonProperty("objects")
Company objects1;
@JsonProperty("objects")
Subject objects2;

但是当我想要解析它时,杰克逊给我一个无法解析的错误,因为我的班级有两个对象(我的意思是json有关键对象,它们的主体有不同的键)

注意:我知道当我有一个对象时我可以解析它...但是我必须这样做,如上所述。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

根据Sfat的评论:This可以是一种方法。

根据我的评论,

我的意思是:

创建如下所示的SubCompany课程,其中包含CompanySubject课程中的所有字段。

public class SubCompany {
    //Just so you can ignore in Json 
    @JsonIgnore
    String type;

    int id;

    // All fields from Company Class
    String companyName;
    String projectName;
    int duration;

    //Remaining fields from Subject Class
    String institutionName;
    String subject;

    //Getters and Setters

    public SubCompany() {
        //At the end call method to test the type
        setType();
    }

    private void setType() {
        if (null != institutionName && null != subject)
            type = "Subject";
        else
            type = "Company";
    }

    //At this point the type is set so you know what you have Company or Subject
    //Now write customized writers.

    public Company getComany() {
        Company company = new Company();
        //Set all the fields accordingly.
        return company;
    }

    public Subject getSubject() {
        //In the similar fashion, write this method to get Subject.
    }

}

如果要在反序列化后检索SubjectCompany对象,请检查SubCompany的类型,并根据具体情况获取相关对象。< / p>

if(type.equals("Subject")
    Subject sub = subCompany.getSubject();