【问题标题】:Gson does not parse json StringGson 不解析 json 字符串
【发布时间】:2022-01-19 14:54:01
【问题描述】:

现在我正在开发一个 Android SDK 项目,代码太旧,我尝试使用 okhttp3 从服务器收集数据。通过使用以下函数,我可以收集来自服务器的响应。

String json = requestGetString(url);

    public String requestGetString(String uri) throws IOException {
    Response res = null;
    try {
        res = getStringHttp(host+uri);
        System.out.println(res.body().string());
        return res.body().string();
    }catch (NullPointerException e) {
        //body = null ??
        throw new IOException(e);
    } catch (IOException e) {
        throw new IOException(e);
    }finally {
        if(res != null){
            try{
                res.close();
            }catch (NullPointerException e){
                //body = null ??
                throw new IOException(e);
            }
        }
    }

}

我正在接收 Json,但我无法用我的数据类解析它。

喜欢下面的

 AuthAppResponse result = parseJson(path, json, AuthAppResponse.class);

你可以看看我的解析器函数

private <TResponse> TResponse parseJson(String path, String json, Class<TResponse> responseClass) throws IOException
{
    return parseJson(getGson(), path, json, responseClass);
}

还有这个,

private <TResponse> TResponse parseJson(Gson gson, String path, String json, Class<TResponse> responseClass) throws IOException
{
    try
    {
        return gson.fromJson(json, responseClass);
    }
    catch (JsonSyntaxException e)
    {
        throw new IOException("The response from '" + path + "' failed to be parsed as JSON.\ncontent = " + json, e);
    }
}

什么都没有发生。

并且具有最新代码库的相同 SDK 可以在相同代码下正常工作。任何人都有想法找出可能的解决方案。 请分享您的评论。

【问题讨论】:

    标签: android json migration gson androidx


    【解决方案1】:

    You can consume an okhttp response body only once。你吃了两次。第一:

    System.out.println(res.body().string());
    

    然后在

    return res.body().string();
    

    【讨论】:

    • 感谢您的回答。我刚刚删除了代码中的那个,然后又试了一次,但问题仍然存在
    【解决方案2】:

    最后我找到了我的代码中缺少的部分,我错过了在旧项目中添加一个proguard 文件,这就是 Gson 不解析响应的原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      相关资源
      最近更新 更多