Сейчас изучаю 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 в качестве моего API в Retrofit:
public interface Api {
String BASE_URL = "my url"
@GET("get-billers")
Call<List<Hero>> getHeroes();
}
В настоящее время понятия не имею, как я могу получить «Код», «сообщение» и массив «billers» и внутри массива billers. Я хочу получить "биллер-код".
Я использовал веб-страницу Пример модернизации 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());
}
});
Я сделал это, и теперь я испытываю "Ожидаемый BEGIN_ARRAY, но был BEGIN_OBJECT в строке 1, столбце 2, путь $"
используйте jsonschema2pojo, сгенерируйте оттуда класс pojo и вставьте свой код.
у вас есть вложенный json, поэтому биллеры будут внутренним классом для вашего основного класса ответа, я не могу получить доступ к этому сайту со своего компьютера, как и после брандмауэра. скопируйте и вставьте свой json и создайте класс pojo.
@FreelancsAndroidLoves, проверь мой ответ. json ответ напрямую назначается модели
Используйте класс модели и вызовите свой метод следующим образом:
@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) {
}
});
Я собираюсь создать две разные модели? Можно ли объединить эти две в один класс?
зависит от ваших требований. вы можете создать два разных класса модели или создать класс модели Biller внутри класса модели Billers.
И напоследок, я попытался вставить свой json в jsonschema2pojo, но он не работает. как ты заставил это работать? Благодарность!
Позвольте нам продолжить обсуждение в чате.
Вы можете создать класс 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();
}
Это способ использования классов POJO в Retrofit. Пожалуйста, попробуйте использовать это так.
В чем разница между этим и другим ответом? Хм.
вам нужно создать класс модели для вашего json и заменить им Hero