我正在尝试使用JSON
将GSON
值映射到POJO。当我尝试从JSON
字符串返回对象时,所有变量都设置为null
这是我的代码
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
对象值始终为null。这是调试器的屏幕截图
更新 JSON响应
{
"Success": true,
"StatusCode": 0,
"StatusMessage": "",
"Data": [
{
"AnalSymptomsMapId": 250,
"SymptomId": 95,
"Symptom": "asdf",
"IsRemoved": false,
"IsSynced": false,
"IsSentToPatient": true
}
]
}
答案 0 :(得分:1)
你能给我们一个Json的例子吗? (像一个字符串)
(JSONObject) jsonArray.get(i).toString()
无论如何,我建议你使用Gson的@SerializedName注释进行映射:
https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html
答案 1 :(得分:0)
将您的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
}
因此,默认值将是原始类型的值。
答案 2 :(得分:0)
我建议您使用this
制作模型JSON
。Gson
。然后您为JSON
生成了一个模型类。
不要忘记实施Parcelable
。
答案 3 :(得分:0)
我建议你试试Ion library by Koush
<强> MODEL 强>
public class PatientSymptoms {
private int AnalSymptomsMapId;
private int SymptomId;
private String Symptom;
private boolean IsRemoved;
private boolean IsSynced;
private boolean IsSentToPatient;
//Getters and Setters
}
<强> USAGE 强>
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中的变量名匹配。