2016-11-28 106 views
0

Pleace,幫我解析JSON。我總是得到一個對象:錯誤的IllegalStateException在Retrofit JSON解析

IllegalStateException異常:預期BEGIN_ARRAY但 行1列2路$

我嘗試收杆List<List<String>><List<String>><String>但得到相同的exeption是BEGIN_OBJECT。

這裏是我的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

您的JSON是不是數組......有啥你預期的 – Selvin

+0

爲什麼不呢? [1,2,3,4]不是數組? JSON數組應該看起來像這樣[{1},{2},{3}]?所以我有對象字符串= [1,2,3,4]? –

+0

{...}不是數組 – Selvin

回答

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

注: - 您要訪問的列表中,但響應它的到來簡單的JSON對象

+0

謝謝,它確實有幫助。 –

+0

歡迎您 – sushildlh