【问题标题】:Dynamically Parse JSON | Android动态解析 JSON |安卓
【发布时间】:2018-09-22 12:01:45
【问题描述】:
    {
  "page" : 0,
  "pageSize" : 15,
  "totalPageCount" : 5,
  "data" : {
    "020" : "Abarth",
    "040" : "Alfa Romeo",
    "042" : "Alpina",
    "043" : "Alpine",
    "057" : "Aston Martin",
    "060" : "Audi",
    "130" : "BMW",
    "095" : "Barkas",
    "107" : "Bentley",
    "145" : "Brilliance",
    "141" : "Buick",
    "150" : "Cadillac",
    "157" : "Caterham",
    "160" : "Chevrolet",
    "170" : "Chrysler"
  }
}

我收到了类似上面的响应,我想使用 GSON 将其解析为 Java 对象,请更新我应该如何解析这个 JSON?

【问题讨论】:

  • JSON 是一种动态的。我不这么认为它的重复
  • 您的 json 格式无效,请查看此处jsonlint.com
  • 刚刚更新了正确的json
  • I am getting a response like above and I want to parse it as JSON 现在是 json。你到底想达到什么目的?你是问如何在android中解析data
  • @ʍѳђઽ૯ท 我现在清楚了吗?

标签: android arrays json gson


【解决方案1】:

解决方案:

请按照以下步骤操作。

首先,创建一个模型类:

public class MyResponse {

    public int page;
    public int pageSize;
    public int totalPageCount;
    public Map<String, String> data;

    (make setter getter for page, pageSize, totalPageCount)

    .......
    .......
}

然后,创建一个自定义类:

class RedirectionInfoDeserializer implements JsonDeserializer<MyResponse> {

    private static final String KEY_PAGE = "page";
    private static final String KEY_PAGESIZE = "pageSize";
    private static final String KEY_TOTALPAGECOUNT = "totalPageCount";
    private static final String KEY_DATA = "data";

    @Override
    public MyResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        final JsonObject jsonObject = json.getAsJsonObject();

        // Read simple String values.
        final String page = jsonObject.get(KEY_PAGE).getAsInt();
        final String pageSize = jsonObject.get(KEY_PAGESIZE).getAsInt();
        final String pageCount = jsonObject.get(KEY_TOTALPAGECOUNT).getAsInt();

        // Read the dynamic parameters object.
        final Map<String, String> data = readParametersMap(jsonObject);

        RedirectionInfo result = new RedirectionInfo();
        result.setUri(uri);
        result.setHttpMethod(httpMethod);
        result.setParameters(parameters);
        return result;
    }

    @Nullable
    private Map<String, String> readParametersMap(@NonNull final JsonObject jsonObject) {
        final JsonElement paramsElement = jsonObject.get(KEY_DATA);
        if (paramsElement == null) {
            // value not present at all, just return null
            return null;
        }

        final JsonObject parametersObject = paramsElement.getAsJsonObject();
        final Map<String, String> parameters = new HashMap<>();
        for (Map.Entry<String, JsonElement> entry : parametersObject.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().getAsString();
            data.put(key, value);
        }
        return data;
    }
}

然后将方法设为:

private Converter.Factory createGsonConverter() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(MyResponse.class, new RedirectionInfoDeserializer());
    Gson gson = gsonBuilder.create();
    return GsonConverterFactory.create(gson);   
}

然后,在您的改造中进行此更改:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myserver.com")
    .addConverterFactory(createGsonConverter())
    .build();

就是这样。

试一试,如果有效,请告诉我。

【讨论】:

  • dataObject.getString("020");是动态值,可以更改
  • 好的,您使用的是 Retrofit 2 吗? @AbdulAleem
  • 是的,我正在使用 Retrofit 2
【解决方案2】:

也许这会对你有所帮助

private void parseJson(JSONObject data) {

        if (data != null) {
            Iterator<String> it = data.keys();
            while (it.hasNext()) {
                String key = it.next();
                try {
                    if (data.get(key) instanceof JSONArray) {
                        JSONArray arry = data.getJSONArray(key);
                        int size = arry.length();
                        for (int i = 0; i < size; i++) {
                            parseJson(arry.getJSONObject(i));
                        }
                    } else if (data.get(key) instanceof JSONObject) {
                        parseJson(data.getJSONObject(key));
                    } else {
                        System.out.println(key + ":" + data.getString(key));
                    }
                } catch (Throwable e) {
                    try {
                        System.out.println(key + ":" + data.getString(key));
                    } catch (Exception ee) {
                    }
                    e.printStackTrace();

                }
            }
        }
    }

【讨论】:

  • 他要求使用GSON,而不仅仅是使用JSON
【解决方案3】:

首先使用下面的代码:

YourPojo obj = new Gson().fromJson(json, YourPojo.class);
//YourPojo is the class you want json to convert to it.
//json is in String format and should be valid(use online validators like jsonlint.com)

第二次使用链接如下:

GSON user's guide

【讨论】:

    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多