繁体   English   中英

在Java中转换Json时遇到问题

[英]Trouble with converting Json in Java

我正在尝试读取一个稍微复杂的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错误还是检索错误。 任何帮助深表感谢!

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

我不由自主地想到了几种解决方法:

  • 更改变量名称以匹配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; ... 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM