Android:将json值映射到pojo

时间:2016-11-17 09:30:23

标签: android json jackson gson pojo

我正在尝试使用JSONGSON值映射到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。这是调试器的屏幕截图

debugger o/p

更新 JSON响应

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

4 个答案:

答案 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

制作模型
  1. 选择来源类型:JSON
  2. 注释样式:Gson
  3. 单击“预览”。
  4. 然后您为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中的变量名匹配。

相关问题