【问题标题】:how gson can identify between a class instance and an array?gson 如何识别类实例和数组?
【发布时间】:2014-06-03 23:21:00
【问题描述】:

我将一些数据发送到我的服务器并得到响应。

如果出现错误,响应是一个类实例:

{
errorCode (int),

errorMsg (String)
}

在成功的情况下,响应是一个 items 数组。

我尝试运行以下代码,但出现错误:

代码:

private void afterServerOfferResponse(final Gson gson,
                        String result) {
                    ServerErrorMessage serverErrorMessage = gson.fromJson(
                            result, ServerErrorMessage.class);

if (serverErrorMessage.errorCode == 0) {
                        Type collectionType = new TypeToken<ArrayList<Offer>>() {
                        }.getType();
                        mOffersList = gson.fromJson(result, collectionType);
                        mAdapter = new ImageAdapter(OffersListActivity.this,
                                mOffersList);
                        mListView.setAdapter(mAdapter);

错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

如何在不过多更改服务器响应的情况下检查错误情况?

【问题讨论】:

    标签: java android json error-handling gson


    【解决方案1】:

    添加一个try-catch 块来处理异常。只有当您尝试解析数据时,才会验证其有效的JSON 响应或错误。

    首先尝试解析Array Class实例,如果JSON异常,则用ServerErrorMessage class解析

    这样添加,Syntax Exception时处理异常

     try{
            ServerErrorMessage serverErrorMessage = gson.fromJson(
                result, ServerErrorMessage.class);
        }catch (JsonSyntaxException e){
            // handle the exception
        }
        catch (JsonIOException e){
            // handle the exception
        }
        catch (JsonParseException e){
            // handle the exception
        }catch (IOException e){
            // handle the exception
        }
    

    另一种方法是像这样使用org.json.JSONObject

      private boolean isValidJsonResponse(String responseString){
        try {
            new JSONObject(responseString);
            return true;
        } catch(JSONException e) {
            return false;
        }
      } 
    

    【讨论】:

    • 但是响应错误和项目列表都是有效的,我只想区分它们。将无错误格式放在catch块中是否正确?
    • 不要在 catch-block 内执行此操作。有两种不同的方法。先调用一个方法用Array Class解析,如果有异常再调用其他方法用Error Message解析
    • 如上所述,将ServerErrorMessage解析移到新方法中,如果响应码有效,则使用Array Class进行解析
    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多