代码之家  ›  专栏  ›  技术社区  ›  Abdul Aleem

动态解析JSON | Android

  •  0
  • Abdul Aleem  · 技术社区  · 6 年前
        {
      "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?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Ümañg ßürmån    6 年前

    解决方案:

    请按照以下步骤操作。

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

    就这样。

    试试看,如果有用就告诉我。

        2
  •  0
  •   KKumar Technologies    6 年前

    也许这对你有帮助

    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();
    
                    }
                }
            }
        }
    
        3
  •  0
  •   hamidrezabstn    6 年前

    首先使用以下代码:

    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