Domanda

I send some data to my server and get a response.

In case there was an error the response is a class instance:

{
errorCode (int),

errorMsg (String)
}

In a success case the response is an items array.

I have tried to run the following code and got an error:

code:

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

error:

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

how would you check for an error case without changing the server response too much?

È stato utile?

Soluzione

Add a try-catch block to handle the exception. Only when you try to parse the data, it will be validated if its valid JSON response or error.

First try to parse Array Class instance and if JSON exception , then parse with ServerErrorMessage class

Add like this, and handle the exception when 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
    }

Another way is to use org.json.JSONObject like this

  private boolean isValidJsonResponse(String responseString){
    try {
        new JSONObject(responseString);
        return true;
    } catch(JSONException e) {
        return false;
    }
  } 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top