[Java] Json parsing

Json-lib

Download address: https://sourceforge.net/projects/json-lib/files/json-lib/

JsonObject method

String jsonString ="{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"}";  
JSONObject json = JSONObject.fromObject(jsonString);  
Student student = new Student();  
student.setId(json.getString("id"));  
student.setName(json.getString("name")); 
student.setSex(json.getString("sex"));  
System.out.println(student.toString()); 

JsonArray way

String jsonString ="{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"},{\"id\":\"2\",\"name\":\"小红\",\"sex\":\"女\"}";  
JSONArray jsonArray = JSONArray.fromObject(jsonString); 
for (int i = 0; i < jsonArray.size(); i++) {  
    Student student = new Student(); 
    student.setId(jsonArray.getJSONObject(i).getString("id"));  
    student.setName(jsonArray.getJSONObject(i).getString("name"));  
    student.setSex(jsonArray.getJSONObject(i).getString("sex"));  
}   

 
 

fastjson

Download address: http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22fastjson%22

JsonObject method

String jsonString = "{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"}";
JSONObject jo = JSONObject.parseObject(jsonString);
System.out.println(jo.getString("id"));
System.out.println(jo.getString("name"));
System.out.println(jo.getString("sex"));

JsonObject method

String jsonString = "{message:\"success\",data:[{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"},{\"id\":\"2\",\"name\":\"小红\",\"sex\":\"女\"}]}";
JSONObject jo = JSONObject.parseObject(jsonString);
JSONArray jsonArray = jo.getJSONArray("data");
for(int i = 0; i < jsonArray.size(); i++){
    System.out.println(jsonArray.getJSONObject(i).getString("id"));
    System.out.println(jsonArray.getJSONObject(i).getString("name"));
    System.out.println(jsonArray.getJSONObject(i).getString("sex"));
}

 
 

summary

Usually, the mutual conversion of json is used with entities, but this project uses data from other systems, the requirements are constantly changing, and the entities are not very fixed, so json has been in a more flexible transformation, only for records, easy to view

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325370557&siteId=291194637