我的响应json像
[{"user":"hasan","name":"hasan hamza"},{"user":"hüseyin","name":"hüseyin tırlak"}]
和我的班级一样
public class Person {
public String user;
public String name;
}
和我的翻新服务界面
public interface IService {
@GET(ServiceURLs.USERS)
Call<List<Person>> getUsers(@Path("operation") String operation);
}
我这样称呼这个界面
retrofit= new Retrofit.Builder()
.baseUrl(ServiceURLs.BASE_SERVICE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IService service = retrofit.create(IService.class);
Call<List<Person>> response = service.getUsers(OperationEnum.SHOW.getOperation());
response.enqueue(new Callback<List<Person>>() {
@Override
public void onResponse(Response<List<Person>> response, Retrofit retrofit) {
if (response.isSuccess()) {
Log.d("Size", response.body().size()+"");
} else {
// error response, no access to resource?
}
}
@Override
public void onFailure(Throwable t) {
// something went completely south (like no internet connection)
Log.d("Error", t.getMessage());
}
});
当我发出此请求时,它落在onFailure方法上,并说
java.lang.IllegalStateException:预期为BEGIN_ARRAY,但在第1行第1列路径$ STRING
我该如何解决
我的配置
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.xyz.damn"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.5.0'
}
最佳答案
OP解决方案。
使用ResponseBody更改服务返回类型
@GET(ServiceURLs.USERS)
Call<ResponseBody> getUsers(@Path("operation") String operation);
然后
Call<LResponseBody> response = service.getUsers(OperationEnum.SHOW.getOperation());
response.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
if (response.isSuccess()) {
Log.d("Size", response.body().size()+"");
try {
String result = response.body().string();
Gson gson = new Gson();
List<LinkedTreeMap> persons = gson.fromJson(result, ArrayList.class);
personList = new ArrayList<>();
for (LinkedTreeMap person : persons) {
personList.add(gson.fromJson(person.toString(), Person.class));
}
} else {
// error response, no access to resource?
}
}
@Override
public void onFailure(Throwable t) {
// something went completely south (like no internet connection)
Log.d("Error", t.getMessage());
}
});
});