Разбор определенного значения в JSON с использованием Retrofit - PullRequest
0 голосов
/ 12 октября 2018

В настоящее время я изучаю Retrofit.Я пытаюсь проанализировать мой ответ JSON, который выглядит следующим образом:

{
    "code": 0,
    "message": "Success",
    "billers": [
        {
            "billerCode": "001 ",
            "billerName": "ABACUS BOOK CARD CORPORATION  ",
            "billerType": "C",
            "label1": "Branch Code                   ",
            "label2": "Origin of Deposit             ",
            "label3": "Collection Date               ",
            "label4": "                              ",
            "label5": "                              "
        },
        {
            "billerCode": "195 ",
            "billerName": "ACCTN INC.                    ",
            "billerType": "C",
            "label1": "Account No.                   ",
            "label2": "Subcriber's Name              ",
            "label3": null,
            "label4": null,
            "label5": null
        },

И в настоящее время я использую его в качестве моего API в Retrofit:

public interface Api {
    String BASE_URL = "my url"

    @GET("get-billers")
    Call<List<Hero>> getHeroes();
}

В настоящее время не знаю, как я могуполучить "Код", "сообщение" и массив "биллеры" и внутри биллеров массива.Я хочу получить "billercode".

Я использовал веб-страницу Пример модификации Android - выборка JSON с URL в качестве справочной информации при изучении Retrofit.

ОБНОВЛЕНИЕ:

Я применил ваш ответ, но потом все равно не могу разобрать содержимое JSON.Вот мой код:

Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) // Here we are using the GsonConverterFactory to directly convert JSON data to object
            .build();
    Api api = retrofit.create(Api.class);
    Call<List<Biller>> call = api.getBillers();

    call.enqueue(new Callback<List<Biller>>() {
        @Override
        public void onResponse(Call<List<Biller>> call, Response<List<Biller>> response) {
            String result = response.body().toString();
            Gson gson = new Gson();
            Type type = new TypeToken<List<Biller>>() {
            }.getType();
            heroList= gson.fromJson(result, type);

            for (int i = 0; i < heroList.size(); i++) {
                DebugUtils.log(""+heroList.get(i).getMessage());
                DebugUtils.log(""+heroList.get(i).getCode());
            }
        }

        @Override
        public void onFailure(Call<List<Biller>> call, Throwable t) {
            DebugUtils.log(""+ t.getMessage());
        }
    });

Ответы [ 2 ]

0 голосов
/ 12 октября 2018

Вы можете создать класс POJO для вышеуказанного содержимого JSON следующим образом:

-----------------------------------com.example.Biller.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Biller {

    @SerializedName("billerCode")
    @Expose
    private String billerCode;

    @SerializedName("billerName")
    @Expose
    private String billerName;

    @SerializedName("billerType")
    @Expose
    private String billerType;

    @SerializedName("label1")
    @Expose
    private String label1;

    @SerializedName("label2")
    @Expose
    private String label2;

    @SerializedName("label3")
    @Expose
    private Object label3;

    @SerializedName("label4")
    @Expose
    private Object label4;

    @SerializedName("label5")
    @Expose
    private Object label5;

    public String getBillerCode() {
        return billerCode;
    }

    public void setBillerCode(String billerCode) {
        this.billerCode = billerCode;
    }

    public String getBillerName() {
        return billerName;
    }

    public void setBillerName(String billerName) {
        this.billerName = billerName;
    }

    public String getBillerType() {
        return billerType;
    }

    public void setBillerType(String billerType) {
        this.billerType = billerType;
    }

    public String getLabel1() {
        return label1;
    }

    public void setLabel1(String label1) {
        this.label1 = label1;
    }

    public String getLabel2() {
        return label2;
    }

    public void setLabel2(String label2) {
        this.label2 = label2;
    }

    public Object getLabel3() {
        return label3;
    }

    public void setLabel3(Object label3) {
        this.label3 = label3;
    }

    public Object getLabel4() {
        return label4;
    }

    public void setLabel4(Object label4) {
        this.label4 = label4;
    }

    public Object getLabel5() {
        return label5;
    }

    public void setLabel5(Object label5) {
        this.label5 = label5;
    }

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

    @SerializedName("code")
    @Expose
    private Integer code;

    @SerializedName("message")
    @Expose
    private String message;

    @SerializedName("billers")
    @Expose
    private List<Biller> billers = null;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<Biller> getBillers() {
        return billers;
    }

    public void setBillers(List<Biller> billers) {
        this.billers = billers;
    }
}

Интерфейс API будет выглядеть следующим образом:

public interface Api {
    String BASE_URL = "my URL"

    @GET("get-billers")
    Call<List<Biller>> getBillers();
}

Thisспособ использовать классы POJO в Retrofit.Пожалуйста, попробуйте использовать это так.

0 голосов
/ 12 октября 2018

Используйте класс модели и назовите свой метод следующим образом:

 @GET("get-billers")
Call<Billers> getBillers();

Класс модели:

public class Biller {

@SerializedName("billerCode")
private String billerCode;

@SerializedName("billerName")
private String billerName;

@SerializedName("billerType")
private String billerType;

@SerializedName("label1")
private String label1;

@SerializedName("label2")
private String label2;

@SerializedName("label3")
private Object label3;

@SerializedName("label4")
private Object label4;

@SerializedName("label5")
private Object label5;

public String getBillerCode() {
return billerCode;
}

public void setBillerCode(String billerCode) {
this.billerCode = billerCode;
}

public String getBillerName() {
return billerName;
}

public void setBillerName(String billerName) {
this.billerName = billerName;
}

public String getBillerType() {
return billerType;
}

public void setBillerType(String billerType) {
this.billerType = billerType;
}

public String getLabel1() {
return label1;
}

public void setLabel1(String label1) {
this.label1 = label1;
}

public String getLabel2() {
return label2;
}

public void setLabel2(String label2) {
this.label2 = label2;
}

public Object getLabel3() {
return label3;
}

public void setLabel3(Object label3) {
this.label3 = label3;
}

public Object getLabel4() {
return label4;
}

public void setLabel4(Object label4) {
this.label4 = label4;
}

public Object getLabel5() {
return label5;
}

public void setLabel5(Object label5) {
this.label5 = label5;
}

}

---------------------- com.test.Billers.java -------------------

public class Billers {

@SerializedName("code")
private int code;

@SerializedName("message")
private String message;

@SerializedName("billers")
private List<Biller> billers = null;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public List<Biller> getBillers() {
return billers;
}

public void setBillers(List<Biller> billers) {
this.billers = billers;
}

}

Обновление: обновите ваш ответ следующим образом.

call.enqueue(new Callback<Billers>() {
     @Override
     public void onResponse(Call<Billers> call, Response<Billers> response) {
         DebugUtils.log(""+response.message());
         DebugUtils.log(""+response.body());
         DebugUtils.log(""+response.toString());


         Billers billers=response.body();
         List<Biller> heroList =  billers.getBillers();
         DebugUtils.log(""+billers.getMessage());

         for (int i = 0; i < heroList.size(); i++) {                 
             DebugUtils.log(""+heroList.get(i).getBillerName());
         }
     }

     @Override
     public void onFailure(Call<Billers> call, Throwable t) {

     }
 });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...