<对象转List<Map<String,String>>>Object转换jsonObject

案例一:
假设有一个对象数据如下:

{
	"data":{	
		"total": 100,
		"page":1,
		"size": 100,
		"record":[
				 {
					"task":"startProduction",
					"startTime":"2022-02-26",
					"endTime":"2022-03-01",
					"taskId":"aaa123"
				 },
				 {
					"task":"endProduction",
					"startTime":"2022-02-26",
					"endTime":"2022-03-01",
					"taskId":"aaa123456"
				} 
			],
		}
	"code":200,
	"message":"success"
}

如何把record数组里面的数据取出来,塞到List>当中去;
直接上代码:


List<Map<String,String>> list = new ArrayList<>();
Result res = data;  // 假设data为上面对象中的数据
Object obj= res.getData();
JSONObject json = (JSONObject) JSONObject.toJSON(obj);  // 关键步骤
JSONArray jsonArray = json.getJSONArray("record");
if(jsonArray.size()>0) {
     for (int i = 0; i < jsonArray.size(); i++) {
         Map<String, Object> map = new HashMap<>();
         JSONObject job = jsonArray.getJSONObject(i);
		 String task = String.valueOf(job.get("task"));
         String taskId= String.valueOf(job.get("taskId"));	
		 map.put("task ",task );
         map.put("taskId",taskId);	
         list.add(map);
     }
 }    

案例二:

{
   "msg_id": "36010000000000221589792383034",
    "device_id": "3601000000000022",
    "device_type":"ZDK",
    "event_time": "1589792383",
    "type": "DEVICE_REPORT",
    "data": {
        "subdev_id": "0101ec1bbdfffebb61c9",
        "group_sid": "0101ec1bbdfffebb61c9",
        "subdev_type": "0101ec1bbdfffebb61c9"
    }
}

当给你这一串东西的时候,后端应该怎么接受呢,不多说了,直接贴代码

@PostMapping(“/test”)
public Object test(@RequestBody Object object) {
JSONObject jsonObject = JSONObject.fromObject(object);
System.out.println(jsonObject.getJSONObject(“data”).getString(“subdev_id”));
return null;
}

重点在于第一句代码,转换
但是要引入一个jar包

net.sf.json-lib
json-lib
2.4
jdk15

你可能感兴趣的:(java,Json,ListMap,list,java,servlet)