Retrofit - 处理具有动态结构的JSON密钥 - Array / Object

时间:2015-07-20 12:31:02

标签: android json parsing retrofit

我正在使用有getter和setter的POJO类。但是,由于这种动态行为,我将被迫使用反序列化部分。我也为此实现了代码,但有没有其他方法来处理这个问题。因为,下面粘贴的响应只是实际响应的一小部分(这是很大的,我正在使用POJO getter和setter)

OBJECT

 secondaryUser: {
    id: 1,
    username: "admin",
    numberOfFollowers: 1,
    displayName: "admin"
    }

ARRAY

 secondaryUser: [
    {
    id: 18150,
    activityDateTime: "2015-07-20 14:46:02",
    user: {
    id: 1,
    username: "admin",
    numberOfFollowers: 1,
    displayName: "admin"
    }
    },
    {
    id: 18148,
    activityDateTime: "2015-07-20 13:35:02",
    user: {
    id: 3,
    username: "USER_1",
    numberOfFollowers: 4,
    displayName: "USER_1"
    }
    },
    {
    id: 18146,
    activityDateTime: "2015-07-20 11:29:41",
    user: {
    id: 2468,
    username: "USER_2",
    numberOfFollowers: 1,
    displayName: "USER_2"
    }
    }
    ]
    }

1 个答案:

答案 0 :(得分:2)

我希望这能解决你的问题。

首先,在您的情况下,如果您已将secondaryUser声明为对象或数组,请将其更改为List<SecondaryUser> secondaryUser

创建反序列化器。

<强> DynamicJsonConverter.java

public class DynamicJsonConverter implements Converter {

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

        }
        return out.toString();
    }

    @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
            return string;

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

您的Rest Adapter类。

<强> BasePathAdapterForDynamicJSONKeys.java

 public class BasePathAdapterForDynamicJSONKeys {
        private static RetroFitInterface topRecommendationsInterface;

        public static RetroFitInterface getCommonPathInterface() {

            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(baseURL)
                    .setConverter(new DynamicJsonConverter())

                    .build();
            topRecommendationsInterface = restAdapter.create(RetroFitInterface.class);
            return topRecommendationsInterface;
        }

此外,请将回调用作Callback<String>()而不是Callback<YourObject>()

现在,在您的活动/片段内,在改造回调的成功方法内,使用此。

@Override
 public void success(String myData, Response response) {
 JSONObject mainObject = null;
 mainObject = new JSONObject(myData);

//You can also use JSONObject, depends on what type the response is

 JSONArray myJsonArray = mainObject.getJSONArray("yourkey");

最后,将其转储到你的arraylist中。(这基本上是将JSON数组转换为arraylist:))

 ArrayList<MyObj> menuDetails = new Gson().fromJson(myJsonArray.toString(), new TypeToken<List<MyObj>>(){}.getType());