Android parses the json array with uncertain key, and the array with irregular format

First look at a piece of json data

{
    
    
	"datas": {
    
    
		"0": {
    
    
			"name": "李雷",
			"gender": "男"
		},
		"1": {
    
    
			"name": "韩梅梅",
			"gender": "女"
		},
		"2": {
    
    
			"name": "Tom",
			"gender": "男"
		}
	}
}

this. . .
If you use GsonFormat to generate beans in android, it will become like this:
insert image description here
Of course, this kind of non-standard json can be called back-end modification, but if he gives you a sentence: "Is this okay for ios? Come on, let's... something like that" what to do? Or all his interfaces are in this format. . . for example:

A real chat with another Android colleague
Well, let's parse this frustrating json:

Take the json shown at the beginning as an example, create a StudentBean, use the GsonFormat plug-in to generate code, only intercept the "array" part, and splicing a key to it (here we take student as an example), as shown in the figure:
insert image description here

 student根据自己的情况命名,头部尾部添加 “{” 、“}”

Let’s analyze the json data again. It is actually an array of datas, but the key is uncertain and can be represented by a Map (the key of the json data is "datas", so the Map here should be named datas):

Map<String,Student> datas;

The final StudentBean looks like this:

public class StudentBean {
    
    
    Map<String,Student> datas;

    public Map<String, Student> getDatas() {
    
    
        return datas;
    }

    public void setDatas(Map<String, Student> datas) {
    
    
        this.datas = datas;
    }

    /**
     * student : {"name":"Tom","gender":"男"}
     */

    private Student student;

    public Student getStudent() {
    
    
        return student;
    }

    public void setStudent(Student student) {
    
    
        this.student = student;
    }

    public static class Student {
    
    
        /**
         * name : Tom
         * gender : 男
         */

        private String name;
        private String gender;

        public String getName() {
    
    
            return name;
        }

        public void setName(String name) {
    
    
            this.name = name;
        }

        public String getGender() {
    
    
            return gender;
        }

        public void setGender(String gender) {
    
    
            this.gender = gender;
        }
    }
}

Parse:

 final String jsonTest = "{
    
    
	"datas": {
    
    
		"0": {
    
    
			"name": "李雷",
			"gender": "男"
		},
		"1": {
    
    
			"name": "韩梅梅",
			"gender": "女"
		},
		"2": {
    
    
			"name": "Tom",
			"gender": "男"
		}
	}
   }";
        Gson gs = new Gson();
        StudentBean bean = gs.fromJson(jsonTest.trim(), StudentBean.class);
        Map<String, StudentBean.Student> studentMap = bean.getDatas();  
        for (String key : studentMap.keySet()) {
    
                            
            System.out.println("key:" + key);
            System.out.println(studentMap.get(key).getName());
            System.out.println(studentMap.get(key).getGender());
        }

StudentBean has correctly described the format of json data, and you can use Gson.formJson to get the entity class;
Map<String, StudentBean.Student>: String corresponds to the uncertain Key in the data: "0", "1", "2" , StudentBean.Student is the data we want to get.
Finally, traverse the map to get the Student data, and output the result:

insert image description here

Dividing line///

Later, data such as this appeared again, and the data field outside was gone =-=:

{
    
    
    "0": {
    
    
        "name": "李雷",
        "gender": "男"
    },
    "1": {
    
    
        "name": "韩梅梅",
        "gender": "女"
    },
    "2": {
    
    
        "name": "Tom",
        "gender": "男"
    }
}

This situation is even simpler, just traverse JSONObject directly:

 String test="{
    
    
    "0": {
    
    
        "name": "李雷",
        "gender": "男"
    },
    "1": {
    
    
        "name": "韩梅梅",
        "gender": "女"
    },
    "2": {
    
    
        "name": "Tom",
        "gender": "男"
    }
};
        try {
    
    
            JSONObject jsonObject = new JSONObject(test);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
    
    
                String key = keys.next();
                StudentBean.Student student = new Gson().fromJson(jsonObject.getString(key), StudentBean.Student.class);
                System.out.println(key +" "+ student.getName() +"  "+ student.getGender());
            }
        } catch (JSONException e) {
    
    
            e.printStackTrace();
        }

Result:
insert image description here
split line ///
and then:

[   
    {
    
    
		"name": "李雷",
		"gender": "男"
	},
	{
    
    
		"name": "韩梅梅",
		"gender": "女"
	},
	{
    
    
		"name": "Tom",
		"gender": "男"
	}
]

All right! In fact, it’s almost the same, let’s go directly to the code:

 String jsonData = "[   \n" +
                "    {\n" +
                "\t\t\"name\": \"李雷\",\n" +
                "\t\t\"gender\": \"男\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"name\": \"韩梅梅\",\n" +
                "\t\t\"gender\": \"女\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"name\": \"Tom\",\n" +
                "\t\t\"gender\": \"男\"\n" +
                "\t}\n" +
                "]";
        System.out.println("jsonData=" + jsonData);
        try {
    
    
            JSONArray itemArray = new JSONArray(jsonData);
            for (int i = 0; i < itemArray.length(); i++) {
    
    
                StudentBean.Student bean = new Gson().fromJson(itemArray.get(i).toString(), StudentBean.Student.class);
                System.out.println(bean.getName());
                System.out.println(bean.getGender());
            }
        } catch (JSONException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_40652755/article/details/109764428