How to handle Dynamic JSON in Retrofit?

后端 未结 10 2344
余生分开走
余生分开走 2020-11-22 16:23

I am using the retrofit efficient networking library, but I am unable to handle Dynamic JSON which contains single prefix responseMessage which changes to

10条回答
  •  不要未来只要你来
    2020-11-22 17:04

    Late to the party, but you can use a converter.

    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);
    

    Then you use a static class which implements retrofit's 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
                }
            } 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("\r\n");
            }
            return out.toString();
        }
    }
    

    I have written this sample converter so it returns the Json response either as String, Object, JsonObject or Map< String, Object >. Obviously not all return types will work for every Json, and there is sure room for improvement. But it demonstrates how to use a Converter to convert almost any response to dynamic Json.

提交回复
热议问题