Parsing dynamic JSON in Android

后端 未结 3 756
遥遥无期
遥遥无期 2020-12-03 23:17

I have a json Object is like this:

{
    Yg7R_: {
    fld_invoice: \"Yg7R_\"
    fld_order_id: \"5\"
        fld_orders: {
            4: {
                f         


        
相关标签:
3条回答
  • 2020-12-04 00:06

    You can do this by one trick. You have to fetch all keys array and corresponding values array of JSONObject. Follow below code.

    JSONObject jsonObj = new JSONObject(JsonResponseString);
    
        JSONArray data1 = jsonObj.getJSONArray("Result");
        JSONObject obj2 = (JSONObject) data1.get(0);
    
        JSONArray nameArray = obj2.names();
        JSONArray valArray = obj2.toJSONArray(nameArray);
    
        String status="";
        String gameId="";
    
        for(int i=0 ; i<valArray.length() ; i++){
            String name = nameArray.getString(i);
            String value = valArray.getString(i);
    
            if (value.equals("null")) {
                value = "";
            }
    
            if (name.equalsIgnoreCase(Constants.Key_1)) {
                Log.v(Constants.LOG, + value);
    
            } else if (name.equalsIgnoreCase(Constants.Key_2)) {
                Log.v(Constants.LOG, + value);
    
            } else if (name.equalsIgnoreCase(Constants.Key_3)) {
                Log.v(Constants.LOG, + value);
    
            } 
        }
    
    0 讨论(0)
  • 2020-12-04 00:11

    You don't have any JSON arrays in there. YOu only have JSON objects. You need to use getJSONObject instead. Arrays are surrounded by [] and may have multiple unnamed objects separated by commas. Objects are surrounded by {} and have a single value with a single name.

    0 讨论(0)
  • 2020-12-04 00:18

    Try this dynamic json parser

    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();
    
                    }
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题