Json字符串转为map或数组或集合

xiaoxiao2021-02-28  10

import java.util.Map; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class Test { @SuppressWarnings("unchecked") public static void main(String[] args) { String json = "{\"user\":\"11\", \"name\":{\"FirstName\":\"tht\",\"LastName\":\"Tang\"}, " + "\"list\":[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]}"; JSONObject Object = JSONObject.parseObject(json); System.out.println(Object); //{"list":[{"name":"a","value":"aa"},{"name":"b","value":"bb"},{"name":"c","value":"cc"},{"name":"d","value":"dd"}],"Name":{"FirstName":"tht","LastName":"Tang"},"UserID":"11"} Integer user =Integer.parseInt(Object.get("user").toString()); System.out.println(user); //11 System.out.println(Object.get("name").toString()); //{"FirstName":"tht","LastName":"Tang"} Map<String,String> name = Object.getObject("name", Map.class); String fName = name.get("FirstName"); System.out.println(fName);//tht JSONArray jsonArray = Object.getJSONArray("list"); System.out.println(jsonArray); //[{"name":"a","value":"aa"},{"name":"b","value":"bb"},{"name":"c","value":"cc"},{"name":"d","value":"dd"}] Map<String,String> listMap = jsonArray.getObject(0, Map.class); System.out.println(listMap.get("name"));//a //转为list List<Map<String, String>> javaObject = JSONArray.toJavaObject(jsonArray, List.class); for (Map<String, String> map : javaObject) { System.out.println(map.get("name")); } String string = jsonArray.getJSONObject(0).get("name").toString(); System.out.println(string); //a } }
转载请注明原文地址: https://www.6miu.com/read-1100056.html

最新回复(0)