简体   繁体   中英

Gson.fromJson does not handle a bad response

I have some code in an Android app where i call a web service and get a json representation of an object back. If successful, it will be a User object. If there is some error, it will be a RestfulStatusResponse object.

I was expecting to get a JsonSyntaxException whenever the response is not a Json string representing a User object, but this does not seem to be the case. Can someone explain why? I created this little test code that illustrates it. The String in the fromJson method call is NOT a User. I do not get an exception here:

package com.my.stuff;

import com.my.stuff.common.User;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.junit.Test;

import okhttp3.HttpUrl;

import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;

public class JsonTest {
    @Test
    public void testFromJson() {
        Gson gson = new Gson();
        try {
            User user = gson.fromJson("{\"restfulResponseMessages\":[{\"message\":\"Invalid information\"}],\"status\":\"900\"}", User.class);
            assertTrue(true);
        }
        catch (JsonSyntaxException e) {
            fail("It failed");
        }
    }
}

The JSON that you're giving to GSON is 100% completely valid. There are no syntax errors in it. So that's why you're not getting a JsonSyntaxException.

Though it will return a User object with completely default values, since it can't map any of the fields from the input JSON to the User object fields.

To handle cases like this, i would return HTTP code 200 from the backend when the request goes well, and then return the User object. If the API call fails, then return HTTP code 400, and return a RestfulStatusResponse object. Then in your API call you check the response code, and parse the object as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM