晚会晚了,但是您可以使用转换器。
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。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)