gpt4 book ai didi

java - Retrofit JSON 解析中出现错误的 IllegalStateException

转载 作者:行者123 更新时间:2023-12-02 03:12:24 24 4
gpt4 key购买 nike

请帮我解析 JSON。我总是得到一个对象:

IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

我尝试解析List<List<String>> , <List<String>><String>但得到同样的异常(exception)。

这是我的 JSON:

{"barcodes":[["1212"],["22222222222"],["22222321321"],["23565233665558488"],["2999300031242"],["6"]]}

界面:

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface RequestInterface {
@GET("barcodeinfo?getBarcodes")
Call<List<List<String>>> getBarcodeList();
}

对象:

public class SingleBarcode {
final String barcodes;

public SingleBarcode(String barcodes) {
this.barcodes = barcodes;
}
}

主要:

void getRetrofitArray() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

RequestInterface service = retrofit.create(RequestInterface.class);

Call<List<List<String>>> call = service.getBarcodeList();

call.enqueue(new Callback<List<List<String>>>() {

@Override
public void onResponse(Call<List<List<String>>> call, Response<List<List<String>>> response) {
try {
List<List<String>> BarcodeData = response.body();
Log.d("MyLog", BarcodeData.size()+"");
} catch (Exception e) {
Log.d("MyLog", "There is an error");
e.printStackTrace();
}
}

@Override
public void onFailure(Call<List<List<String>>> call, Throwable t) {
Log.d("MyLog", "error " + t.toString());
}
});
}

最佳答案

use these POJO class

public class Result {

@SerializedName("barcodes")
@Expose
private List<List<String>> barcodes = new ArrayList<List<String>>();

/**
*
* @return
* The barcodes
*/
public List<List<String>> getBarcodes() {
return barcodes;
}

/**
*
* @param barcodes
* The barcodes
*/
public void setBarcodes(List<List<String>> barcodes) {
this.barcodes = barcodes;
}

}

use interface like this ...

@GET("barcodeinfo?getBarcodes")
Call<Result> getBarcodeList();

and call like this ....

  Call<Result> call = service.getBarcodeList();

call.enqueue(new Callback<Result>() {

@Override
public void onResponse(Call<Result> call, Response<Result> response) {

Result r = response.body(); // you can initialize result r variable global if you have out side use of this response

}

@Override
public void onFailure(Call<Result> call, Throwable t) {
Log.d("MyLog", "error " + t.toString());
}
});

注意:- 您正在尝试作为 LIST 进行访问,但作为响应,它会出现简单的 JSON OBJECT

关于java - Retrofit JSON 解析中出现错误的 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40841256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com