使用Retrofit读取JSON

时间:2017-02-15 07:58:12

标签: android json retrofit retrofit2

我试图读取我的Json,但我不知道如何将这个json响应映射到它们的基本元素中。

这就是我的Json的样子:

    [
      {
       12345: {
           L Hendrik: {
             CU.Administration ID: "12345_LJ",
             CU.Customer ID: "L Hendrik",
             CU.Name: "Coffeecompany L Hendrik"
             }
          }
]

“12345”是动态ID, “L Hendrik”是一个动态名称

我的代码:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("URLTOMYAPI")
            .addConverterFactory(GsonConverterFactory.create())
            .build();


APIService service = retrofit.create(APIService.class);
    Call<List<Student>> call = service.getStudentDetails();

    call.enqueue(new Callback<List<Student>>() {
        @Override
        public void onResponse(Call<List<Student>> call, Response<List<Student>> response) {
            List<Student> students = response.body();

            String details = "";

            for(int i = 0; i<students.size(); i++){
                String name = students.get(i).getName();

                details += "\n\nname: " + name;
            }
            textDetails.setText(details);
            pDialog.hide();
        }

        @Override
        public void onFailure(Call<List<Student>> call, Throwable t) {
            pDialog.hide();
            Log.v("Test", "Failluree?");

            Log.v("Test", "Failluree?" + t);

        }
    });

和我的Pojo

public class Student implements Serializable {

    private String name, address, custId;
    private int mobile;

    public String getCustId() {
        return custId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

我知道Pojo不正确,但我不知道如何从这个Json获取信息。

1 个答案:

答案 0 :(得分:0)

也许你不能通过GSON解析Json,你应该手动解析Json。像这样:

APIService service = retrofit.create(APIService.class);
Call<JSONArray> call = service.getStudentDetails();

call.enqueue(new Callback<JSONArray>() {
    @Override
    public void onResponse(Call<JSONArray> call, Response<JSONArray> response) {
        for(int idx = 0; idx < response.length(); idx++) {
           JSONObject jsonObject = response.get(idx);
           Iterator<String> keys = jsonObject.keys();
           while (keys.hasNext()) {
           JSONObject object = jsonObject.optJSONObject(keys.next()).getJSONObject("L Hendrik");
                if (object != null) {
                    Student student = new Student();
                    student.setName(object.optString("CU.Administration ID"));
                    // Other parse .   
                }
           }
       }
    }

    @Override
    public void onFailure(Call<List<Student>> call, Throwable t) {
        pDialog.hide();
        Log.v("Test", "Failluree?");

        Log.v("Test", "Failluree?" + t);

    }
});