2016-07-12 5 views
0

다소 복잡한 json 문자열을 읽으려고하고 중첩 된 항목 및이를 검색하는 방법에 문제가 있습니다. 내가 널 포인트 예외 여기Java에서 Json을 변환 할 때 문제가 발생했습니다.

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

null 부분은 무엇입니까? – SLaks

+0

문자열 firstName = sample.getPatient(). getName(). getGiven(); 은 널 포인터 예외를 반환하고 있습니다. – 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의 모든 항목에 문제가있을 수 있습니다.

관련 문제