2016-07-12 6 views
0

多少複雑なjson文字列を読み込もうとしていますが、入れ子になっている項目やそれらを取得する方法に問題があります。JavaでJsonを変換する際に問題があります

私のJavaコードは、私がここでヌル点例外

を取得し、いずれかのアプローチは、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" 
      } 
     } 
    } 

で実行すると、以下の

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); 

のように見えます私のクラスです:

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を間違って格納しているか間違って取得しているかどうかはわかりません。どんな助けでも大歓迎です!

+0

ヌルはどの部分ですか? – SLaks

+0

文字列firstName = sample.getPatient()。getName()。getGiven(); がNULLポインタ例外を返す – mmm2893

答えて

0

フィールド名がJSONと一致しないため、null患者フィールドのPrescriptionReqオブジェクトが戻ってきています。私の頭の上オフ

、私はこの問題を解決するにはカップルの方法を考えることができます。

  • 変更、追加

    public class PrescriptionReq { 
        // have to rename Patient class to avoid name collision 
        private PRPatient Patient; 
    ... 
    
  • JSONフィールドと一致する変数の名前@SerializedName「実際の」フィールド名が何であるかをGsonに伝えるための注釈

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

もちろん、nameフィールドのPatientクラスのフィールドと、Addressの何かに問題があります。

関連する問題