栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带有Retrofit API的MalformedJsonException?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带有Retrofit API的MalformedJsonException?

com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException: UseJsonReader.setLenient(true)
通常是在某些字符格式不正确的JSON时抛出。异常消息本身建议使反序列化更加容忍。

但是我建议您修复JSON并从不需要的字符中修剪掉它。

您应该扩展

GsonConverter

和覆盖
fromBody()
Gson
从宽容中读取
JsonReader
。然后将其设置为您的
RestAdapter
JsonReader
如果没有抛出异常,这将尝试使用宽容反序列化,然后将其关闭。

public class LenientGsonConverter extends GsonConverter {private Gson mGson;public LenientGsonConverter(Gson gson) {    super(gson);    mGson = gson;}public LenientGsonConverter(Gson gson, String charset) {    super(gson, charset);    mGson = gson;}@Overridepublic Object fromBody(TypedInput body, Type type) throws ConversionException {    boolean willCloseStream = false; // try to close the stream, if there is no exception thrown using tolerant  JsonReader    try {        JsonReader jsonReader = new JsonReader(new InputStreamReader(body.in()));        jsonReader.setLenient(true);        Object o = mGson.fromJson(jsonReader,type);        willCloseStream = true;        return o;    } catch (IOException e) {        e.printStackTrace();    }finally {        if(willCloseStream) { closeStream(body);        }    }    return super.fromBody(body, type);}private void closeStream(TypedInput body){        try { InputStream in = body.in(); in.close();        } catch (IOException e) { e.printStackTrace();        }    }}

}



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437122.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号