我是第一次使用Retrofit2,并且在以非JSON格式获取简单数组时遇到问题。
错误:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $[0]
这意味着它不是JSON对象,因为它不以“{”
开头我尝试添加 ScalarsConverter ,但它似乎无效。
Api:https://chasing-coins.com/api/v1/coins
界面:
public interface Retro_coins {
@GET("api/v1/coins")
Call<List<Coinlist>> getCoinlist();
}
班级:
public class Coinlist {
private List coinlist;
public List getCoinlist() {
return coinlist;
}
}
改造初始化并致电:
String API_BASE_URL = "https://chasing-coins.com/";
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
;
Retrofit retrofit = builder.client(httpClient.build()).build();
Retro_coins client = retrofit.create(Retro_coins.class);
// Fetch list
Call<List<Coinlist>> call =
client.getCoinlist();
// Execute the call asynchronously. Get a positive or negative callback.
call.enqueue(new Callback<List<Coinlist>>() {
@Override
public void onResponse(Call<List<Coinlist>> call, Response<List<Coinlist>> response) {
// The network call was a success and we got a response
Log.w("Yes", response.toString());
}
@Override
public void onFailure(Call<List<Coinlist>> call, Throwable t) {
Log.w("no", t.toString());
}
});
谢谢!
答案 0 :(得分:1)
当您使用private List coinlist;
时,Gson希望该对象为
{
"coinlist":"[]"
}
你所提供的只是
["String","String","String"]
此外,当您使用Call<List<Coinlist>>
时,您希望数据为
[
{
"coinlist":"[]"
}
]
只需将您的来电从Call<List<Coinlist>>
更改为Call<List<String>>
即可。这应该可以解决你的问题。如果您需要更多说明,请告诉我
答案 1 :(得分:0)
您的请求返回字符串。因此,您需要将响应更改为字符串或需要更改您的请求调用字符串。