【发布时间】:2018-07-02 15:32:55
【问题描述】:
我是第一次使用 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());
}
});
谢谢!
【问题讨论】:
-
因为你的对象是错误的。你正在获取的只是一个字符串列表
-
如果您不使用 JSON,则不需要 addConverterFactory(GsonConverterFactory.create()) 使用您期望的格式
标签: android json http retrofit