Gson.fromJson不会处理不良响应 [英] Gson.fromJson does not handle a bad response

查看:412
本文介绍了Gson.fromJson不会处理不良响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android应用程序中有一些代码,在其中我调用Web服务并获取对象的json表示形式.如果成功,它将是一个User对象.如果出现错误,它将是一个RestfulStatusResponse对象.

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.

每当响应不是代表User对象的Json字符串时,我都希望得到JsonSyntaxException,但事实并非如此.有人可以解释为什么吗?我创建了这个小测试代码来说明这一点. fromJson方法调用中的String不是User.我在这里没有例外:

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

推荐答案

您提供给GSON的JSON 100%完全有效.其中没有语法错误.因此,这就是为什么您没有收到JsonSyntaxException的原因.

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.

尽管它将返回具有完全默认值的User对象,因为它无法将输入JSON中的任何字段映射到User对象字段.

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.

要处理这样的情况,当请求顺利进行时,我将从后端返回HTTP代码200,然后返回User对象.如果API调用失败,则返回HTTP代码400,并返回RestfulStatusResponse对象.然后在您的API调用中,检查响应代码,并根据需要解析对象.

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.

这篇关于Gson.fromJson不会处理不良响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆