Android:Mapping json 值到 pojo

Android:Mapping json values to pojo

我正在尝试使用 GSONJSON 值映射到 POJO。当我尝试从 JSON 字符串中取回对象时,所有变量都设置为空。
这是我的代码

Pojo.java

public class PatientSymptoms {

    private Integer AnalSymptomsMapId;
    private Integer SymptomId;
    private String Symptom;
    private Boolean IsRemoved;
    private Boolean IsSynced;
    private Boolean IsSentToPatient;

    //Getters and Setters
}

映射码

JSONObject jsonObject = (JSONObject) jsonArray.get(i);
PatientSymptoms symptoms = new PatientSymptoms();

Gson gson = new Gson();
String x =  gson.toJson(jsonObject);
symptoms = gson.fromJson(x,PatientSymptoms.class);

PatientSymptoms 对象值始终为空。这是调试器的屏幕截图

已更新 JSON 回复

{
  "Success": true,
  "StatusCode": 0,
  "StatusMessage": "",
  "Data": [
    {
      "AnalSymptomsMapId": 250,
      "SymptomId": 95,
      "Symptom": "asdf",
      "IsRemoved": false,
      "IsSynced": false,
      "IsSentToPatient": true
    }
  ]
}

让你的Pojo.java成为

    public class PatientSymptoms {

    private int AnalSymptomsMapId;
    private int SymptomId;
    private String Symptom;
    private boolean IsRemoved;
    private boolean IsSynced;
    private boolean IsSentToPatient;

    //Getters and Setters
}

因此,默认值将是基本类型的值。

你能给我们举个例子Json吗? (像一个字符串)

(JSONObject) jsonArray.get(i).toString()

无论如何,我建议您使用 Gson 中的 @SerializedName 注释来进行映射:

https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

我建议使用 this

制作您的模型
  1. 选择来源类型:JSON
  2. 注释样式:Gson.
  3. 点击预览。

那么您已经为您的JSON生成了一个模型Class。

并且不要忘记实现 Parcelable

我推荐你试试Ion library by Koush

型号

public class PatientSymptoms {

       private int AnalSymptomsMapId;
       private int SymptomId;
       private String Symptom;
       private boolean IsRemoved;
       private boolean IsSynced;
       private boolean IsSentToPatient;

    //Getters and Setters
}

用法

Ion.with(context)
   .load("http://example.com/api/patient")
   .as(new TypeToken<List<PatientSymptoms>>(){})
   .setCallback(new FutureCallback<List<PatientSymptoms>>() {
       @Override
       public void onCompleted(Exception e, List<PatientSymptoms> symptoms) {
            // Use the list of Patient Symtoms
    }
});

注意:你唯一需要记住的是JSON键应该匹配POJO或MODEL中的变量名。