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

如何在翻新中处理动态JSON?

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

如何在翻新中处理动态JSON?

晚会晚了,但是您可以使用转换器。

RestAdapter restAdapter = new RestAdapter.Builder()    .setEndpoint("https://graph.facebook.com")    .setConverter(new DynamicJsonConverter()) // set your static class as converter here    .build();api = restAdapter.create(FacebookApi.class);

然后,您使用一个静态类来实现改装的Converter:

static class DynamicJsonConverter implements Converter {    @Override public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {        try { InputStream in = typedInput.in(); // convert the typedInput to String String string = fromStream(in); in.close(); // we are responsible to close the InputStream after use if (String.class.equals(type)) {     return string; } else {     return new Gson().fromJson(string, type); // convert to the supplied type, typically Object, JsonObject or Map<String, Object> }        } catch (Exception e) { // a lot may happen here, whatever happens throw new ConversionException(e); // wrap it into ConversionException so retrofit can process it        }    }    @Override public TypedOutput toBody(Object object) { // not required        return null;    }    private static String fromStream(InputStream in) throws IOException {        BufferedReader reader = new BufferedReader(new InputStreamReader(in));        StringBuilder out = new StringBuilder();        String line;        while ((line = reader.readLine()) != null) { out.append(line); out.append("rn");        }        return out.toString();    }}

我已经编写了此样本转换器,因此它以字符串,对象,JsonObject或Map
<字符串,对象>的形式返回Json响应。显然,并非所有返回类型都适用于每个Json,并且肯定有改进的空间。但是它演示了如何使用Converter将几乎所有响应转换为动态Json。



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

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

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