动态解析JSON |安卓系统

时间:2018-09-22 12:01:45

标签: android arrays json gson

    {
  "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 Object,请更新我该如何解析此JSON?

3 个答案:

答案 0 :(得分:1)

解决方案:

请按照以下步骤操作。

首先,创建一个模型类:

import Foundation

class myThread: Thread
{
    override func main() {
        while(true) {
            print("Running in the Thread");
            Thread.sleep(forTimeInterval: 4);
        }
    }
}

let t = myThread();
t.start();

while(true) {
    print("Main Loop");
    sleep(5);
}

然后,将自定义类设置为:

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

就是这样。

尝试一下,让我知道它是否有效。

答案 1 :(得分:0)

也许这会对您有帮助

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

                }
            }
        }
    }

答案 2 :(得分:0)

首先使用以下代码:

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