将JSON响应映射到相应的POJO

时间:2019-01-31 03:55:07

标签: java android json gson

从json获得响应时,我的项目有问题。

这是我的JSON结构

{
"RC": "00",
"FakturPengajuan": "PO201901310000000007",
"Plafond": "1,000,000.00",
"Pokok": "500,000.00",
"Bunga": "10,000.00",
"TotalBayar": "510,000.00",
"JT": {
    "1": {
        "Ke": 1,
        "JatuhTempo": "28 Februari 2019",
        "Pokok": "500,000.00",
        "Bunga": "10,000.00",
        "Jumlah": "510,000.00",
        "BakiDebet": "500,000.00"
    },
    "2": {
        "Ke": 2,
        "JatuhTempo": "31 Maret 2019",
        "Pokok": "500,000.00",
        "Bunga": "10,000.00",
        "Jumlah": "510,000.00",
        "BakiDebet": "0.00"
    }
}

}

这是我的回复代码

@Override
        public void onFinish(String cResponse) {
            String cError = null;
            if (cResponse != null){
                try{
                    Response response = gson.fromJson(cResponse,Response.class);
                    if (response != null && response.getRC() != null){
                        if (response.getRC().equals("00")){



                        }else cError = response.getMSG();
                    }else{
                        cError = "Error";
                    }
                }catch (Exception e){
                    cError = "Error" + e.getMessage();
                    FuncApp.showLog("Response " + e.getMessage());
                }

            }else cError = "Gagal";
            if (cError != null)
                new FuncApp.OkNoDialog(getActivity(),"Gagal Aktivasi",cError ,null,"OK").setOnFinish(new FuncApp.OkNoDialog.ButtonClick() {
                    @Override
                    public void onClick(Boolean isOKButton) {

                    }
                });

            funcApp.closeProgresDialog();
        }

这是我的响应获取器和设置器,不是全部,只是我使用的所有变量。

public class Response {
private String RC;
private String FakturPengajuan, Plafond, Pokok, Bunga, TotalBayar;
private String[] JT;

public Response(){}
  }

获取响应时出现此错误,代码应该是什么?

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

1 个答案:

答案 0 :(得分:1)

POJO类Response具有一些无效的结构字段JTMap而不是数组,您应该具有getter和setter方法

public class Response {
private String RC;
private String FakturPengajuan, Plafond, Pokok, Bunga, TotalBayar;
private Map<String,MapValue> JT;

 public Response(){}
  }

地图值类

public class MapValue {

 private int Ke;
 private String JatuhTempo;
 private String Pokok;
 private String Bunga;
 private String Jumlah;
 private String BakiDebet;

 }