改进JSON解析

时间:2016-11-28 09:46:06

标签: java android json retrofit2

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

  

IllegalStateException:预期为BEGIN_ARRAY但是BEGIN_OBJECT为   第1行第2列路径$

我尝试分析List<List<String>><List<String>><String>,但获得相同的例外。

这是我的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();
}

OBJ:

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());
        }
    });
}

1 个答案:

答案 0 :(得分:2)

  

使用这些POJO类

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;
}

}
  

使用这样的界面...

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

并像这样打电话......

  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