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(); } }}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)