【发布时间】:2018-02-17 11:24:22
【问题描述】:
onFailure 在改造中抛出此异常“预期 BEGIN_ARRAY 但在第 1 行第 1 列路径 $ 上为字符串”,如果我从 gson 转换器中删除 setLinient(true),则同一行 1 列 1 会再抛出一个异常“格式错误的 json”和这是突然发生的,以前它工作正常,我很难分析导致这个问题的变化,有人可以看看这个并帮助我,
我有这个来自服务器的 Json 响应:
[{
"disposal_type_category": {
"category_entry_total": "21"
},
"disposal_types": [{
"ID": "78",
"entries": [{
"ID": 2584,
"entry_tally": "1"
},
{
"ID": 2578,
"entry_tally": "1"
}
]
},
{
"ID": "1323",
"entries": [{
"ID": 2583,
"entry_tally": "1"
},
{
"ID": 2579,
"entry_tally": "1"
}
]
}
]
},
{
"disposal_type_category": {
"category_entry_total": "25.2"
},
"disposal_types": [{
"ID": "80",
"entries": [{
"ID": 2583,
"entry_tally": "1"
},
{
"ID": 2579,
"entry_tally": "1"
}
]
},
{
"ID": "84",
"entries": [{
"ID": 2583,
"entry_tally": "1"
},
{
"ID": 2579,
"entry_tally": "1"
}
]
}
]
}]
这是我的改造代码:
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
String token = prefs.getString("token", "No name defined");//"No name defined" is the default value.
Call<List<Disposal>> callm = apiService.getCollection(token);
callm.enqueue(new Callback<List<Disposal>>() {
@Override
public void onResponse(Call<List<Disposal>> call, Response<List<Disposal>> response) {
if (response.body() != null) {
EntriesList = response.body();
setRecyclerData(0);
}
}
@Override
public void onFailure(Call<List<Disposal>> call, Throwable t) {
}
});
这是在我的 ApiClient.java 中:
public static Retrofit getClient() {
if (retrofit==null) {
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
这是在 ApiInterface.java 中:
Call<List<Disposal>> getCollection(@Header("Authorization") String token);
Disposal.java:
public class Disposal {
@SerializedName("disposal_type_category")
@Expose
public DisposalTypeCategory disposalTypeCategory;
@SerializedName("disposal_types")
@Expose
public List<DisposalType> disposalTypes = null;
}
DisposalTypeCategory.java:
public class DisposalTypeCategory {
@serializedname("category_entry_total")
@expose
public String categoryEntryTotal;
}
DisposalType.java:
public class DisposalType {
@serializedname("ID")
@expose
public String iD;
@serializedname("entries")
@expose
public List<Entries> entries = null;
}
Entries.java:
public class Entries {
@serializedname("ID")
@expose
private int iD;
@SerializedName("entry_tally")
@Expose
private String entryTally;
}
我已经为 Gson 设置了 setLineant(true),因为如果我删除它,我会得到格式错误的 json 异常,即使这个问题最近开始也很好,不确定它是否相关。 在向 API 添加了 2-3 个新字段并且更改了基本 url 但核心仍然保持不变之后,问题就开始了。
【问题讨论】:
-
改造期望一个数组并找到字符串
-
在此处发布改造代码
-
尝试记录响应,可能是 api 正在生成错误而不是预期的 json。
-
是的,但是如果您看到响应返回的是数组而不是字符串,这就是我感到困惑的原因,我将使用改造代码更新问题
-
大家请在 cmets 中投下反对票的原因,以便我更正,谢谢
标签: android json retrofit2 gson