1

I'm getting a response from Server and I deserialize it using Gson to the corresponding Object.

The problem is that sometimes I get an error response ( which is ofcourse not of type of the Object I expect ) and that leads to NullPointerException. How can I handle such a case?

My code is :

        Response pollsResponse = okHttpClient.newCall(pollsRequest).execute();

        String pollsResponseString = pollsResponse.body().string();

        // Gson Type for List of Poll.class oObjects
        Type listType = new TypeToken<ArrayList<Poll>>() { }.getType();
        pollsList = gson.fromJson(pollsResponseString, listType);

When there's an error last line of code gives NPE. How am I going to check if item is not type of ArrayList<Poll> so I won't deserialize it ?

Edit: I can't understand why my question is similar to the one linked ? I know what is a NPE. I don't know how I can handle a result I don't expect from a network call which will lead to NPE. Correct my if I'm wrong.

Mes
  • 1,671
  • 3
  • 20
  • 36
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –  Jun 08 '16 at 13:54

1 Answers1

1

You need to check that the Response is valid before you attempt to parse the body. Something like this:

if (!pollsResponse.isSuccessful()) 
    throw new IOException("Unexpected reply " + pollsResponse);

See the recipe here: https://github.com/square/okhttp/wiki/Recipes

BTW: The issue with your question is that the subject "NPE when deserializing..." isn't really pertinent to the problem, a better subject might be "How can I look for OKHttp response errors?"

Matthew
  • 10,361
  • 5
  • 42
  • 54
  • Yes you are right. I thought it has something to do with java. Sorry my bad, thanks for the answer and your point. – Mes Jun 08 '16 at 14:11
  • 1
    @Mes - no problem. Note that this won't fully cover you if the server one day decides not to send you JSON - e.g. if it moves home, or is hacked, or similar. I'm sure you're less worried about these edge cases, but never forget that something you don't control could potentially send you anything! – Matthew Jun 08 '16 at 14:13
  • That's true, but right now is the least of my worries :P – Mes Jun 08 '16 at 14:20