public static void main(String[] args) { List list = new ArrayList<>(); HashMap map = new HashMap<String,Object>(); map.put("name", "zhou"); map.put("age", 20); map.put("Address", "hubei"); map.put("career", "student"); list.add(map); HashMap map1 = new HashMap<String,Object>(); map1.put("name", "zhangsan"); map1.put("age", 30); map.put("Address", "wuhan"); map.put("career", "teacher"); list.add(map1); System.out.println(list); JSONArray result = JSONArray.fromObject(list); List<Person> jsonDtosList = (List<Person>) JSONArray.toCollection(result, Person.class); System.out.println(jsonDtosList);
net.sf.json.JSONArray; 的
JSONArray.fromObject(list); 可以把 包含 hashMap 的 List 轉化成
JSONArray (每一個元素是 JSONObject),
List<Person> jsonDtosList = (List<Person>) JSONArray.toCollection(result, Person.class); 把
JSONArray 轉化成 對象數組。
對象的構造函數必須是默認的無參構造函數。對象中沒有的字段都是 null
package stream; public class Person { private String name; private int age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } /* * public Person(String name, int age) { * * this.name = name; this.age = age; } */ }
一: HashMap 直接轉化成 JSONObject:
map.put("title",title);
map.put("content",text);
net.sf.json.JSONObject jsonObject= JSONObject.fromObject(map);
二:HashMap 直接轉化成 JSONObject:
map.put("title",title);
map.put("content",text);
com.alibaba.fastjson.JSONObject.JSONObject jsonObject= JSONObject.parseObject(JSON.toJSONString(map));
三: 使用 hutool 包的 JSONObject 可以把 json形式的字符串轉化成 JSONObject 對象,此對象中每一個元素都是HashMap 對象,可以使用 map.putAll 保存到HashMap中。
並且 可以使用jsonObject.get(String key) 來獲取元素。
String strq="{\"pfid\":\"1164806502843756545\",\"nickName\":\"楊老師\"}"; cn.hutool.json.JSONObject jsonObject = cn.hutool.json.JSONUtil.parseObj(strq); Map<String, Object> data = new HashMap<String, Object>(); data.putAll(jsonObject); System.out.println(data); System.out.println(data.get("pfid")); String nickName = (String) jsonObject.get("nickName"); System.out.println(nickName);