在Java中转换Json的麻烦

时间:2016-07-12 16:51:22

标签: java json

我正在尝试阅读一个有点复杂的json字符串,我遇到嵌套项目的问题以及如何检索它们。

我的java代码如下所示

String longJson = "{'Patient': {'Name': {'Given': 'FirstName','Family': 'LastName'},'Gender': 'Female','DOB': '1980-07-04T00:00:00.0000000','AgeInYears': 36,'MartialStatus': 'Single', 'Race': 'Race','Ethnicity': 'Ethnicity','Class': 'Inpatient','Address': {'StreetAddress': 'StreetAddress','City': 'City','State': 'State','ZipCode': 'ZipCode', 'Country': 'Country'}}}";

    Gson gson = new Gson();

    PrescriptionReq sample = null;
    sample = gson.fromJson(longJson, PrescriptionReq.class);


    String firstName = sample.getPatient().getName().getGiven();
    //String firstName = sample.patient.name.getGiven();
    System.out.println("Testing: "+ firstName);

当我运行任何一种方法时,我都会得到零点异常

这是一个更易读的视图中的Json

        {
        "Patient": {
            "Name": {
                "Given": "FirstName",
                "Family": "LastName"
            },
            "Gender": "Female",
            "DOB": "1980-07-04T00:00:00.0000000",
            "AgeInYears": 36,
            "MartialStatus": "Single",
            "Race": "Race",
            "Ethnicity": "Ethnicity",
            "Class": "Inpatient",
            "Address": {
                "StreetAddress": "StreetAddress",
                "City": "City",
                "State": "State",
                "ZipCode": "ZipCode",
                "Country": "Country"
            }
        }
    }

以下是我的课程:

public class PrescriptionReq {
private Patient patient;

public Patient getPatient(){
    return patient;
}

public class Patient {
    Name name;
    Address address;

    public Name getName(){
        return name;
    }
    //Other variables
   }

public class Name {
    private String Given;
    private String Family;

    public String getGiven() {
        return Given;
    }

    public String getFamily() {
        return Family;
    }

   }
}

我不确定我是否存储错误的json或检错。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您的字段名称与您的JSON不匹配,因此您将获得一个PrescriptionReq患者字段的null对象。

在我的头脑中,我可以想到几种方法来解决这个问题:

  • 更改变量的名称以匹配JSON字段

    public class PrescriptionReq {
        // have to rename Patient class to avoid name collision
        private PRPatient Patient;
    ...
    
  • 添加@SerializedName注释以告诉Gson“真实”字段名称是什么

    public class PrescriptionReq {
        @SerializedName("Patient")
        private Patient patient;
    ...
    

当然,您还需要为name课程中的Patient字段以及您遇到问题的Address中的任何内容执行此操作。