2017-07-14 190 views
0

我有我的JSON作为:JsonSyntaxException预计BEGIN_OBJECT但BEGIN_ARRAY在路径

{ 
"status": "true", 
"rows": [ 
    { 
     "rec_time": "2017-05-02 11:08:00 " 
    }, 
    { 
     "rec_time": "2017-05-02 10:08:15 " 
    } 
], 
"total": 10000, 
"code": 200 

}

我RowsBean模型:

public class RowsBean<T> extends BaseBean { 


    private T rows; 
    private int total; 


    public T getRows() { 
     return rows; 
    } 

    public void setRows(T rows) { 
     this.rows = rows; 
    } 

    public int getTotal() { 
     return total; 
    } 

    public void setTotal(int total) { 
     this.total = total; 
    } 

} 

public class DataBean { 

    private String rec_time; 

    public String getRec_time() { 
     return rec_time; 
    } 

    public void setRec_time(String rec_time) { 
     this.rec_time = rec_time; 
    } 

而且我GSON定制解串器如下:

public class RowsJsonDeser implements JsonDeserializer<RowsBean<?>> { 

    @Override 
    public RowsBean<?> deserialize(JsonElement json, Type typeOfT, 
            JsonDeserializationContext context) throws JsonParseException { 

     RowsBean resultBean = new RowsBean(); 
     if (json.isJsonObject()) { 
      JsonObject jsonObject = json.getAsJsonObject(); 

      Type type = ((ParameterizedType) typeOfT).getActualTypeArguments()[0]; 
      resultBean.setRows(context.deserialize(jsonObject.get("rows"),type)); 


     } 
     return resultBean; 
    } 
} 

我正在使用Retrofit库,它使用gson来序列化/反序列化json对象。我通过这个自定义的gson解串器进行改进,但它给了我一个错误。

如果jsonObject.get( “行”)是的JSONObject,该代码是正确的,但现在, jsonObject.get( “行”)是jsonArray

错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $ 

你能告诉我在去行列的时候哪里出错了?

回答

1

相反的jsonObject.get("rows"),使用下面syndax

jsonObject.getAsJsonArray("rows")

+1

您的回答是我的问题的完美解决方案,谢谢 –

0

除了Mani的评论,我认为你可能会遇到更多的问题,因为rows是行类型,T的数组。看起来您应该将RowsBean的实施更改为包含rows类型的T[]而不是T

+0

感谢您的帮助,我改进了代码并将它用在实现类中。像这样Observable >> –

相关问题