HashMap ArrayList 和 List对象的转换 | 您所在的位置:网站首页 › list对象转listmap › HashMap ArrayList 和 List对象的转换 |
public static void main(String[] args) {
List list = new ArrayList();
HashMap map = new HashMap();
map.put("name", "zhou");
map.put("age", 20);
map.put("Address", "hubei");
map.put("career", "student");
list.add(map);
HashMap map1 = new HashMap();
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 jsonDtosList = (List) JSONArray.toCollection(result, Person.class);
System.out.println(jsonDtosList);
net.sf.json.JSONArray; 的 JSONArray.fromObject(list); 可以把 包含 hashMap 的 List 转化成 JSONArray (每一个元素是 JSONObject), List jsonDtosList = (List) 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 data = new HashMap(); data.putAll(jsonObject); System.out.println(data); System.out.println(data.get("pfid")); String nickName = (String) jsonObject.get("nickName"); System.out.println(nickName);
|
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |