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);

 

相关文章:

  • 2022-01-02
  • 2022-03-07
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-19
猜你喜欢
  • 2021-11-29
  • 2022-02-11
  • 2021-12-09
  • 2022-01-23
  • 2021-07-09
  • 2022-12-23
  • 2021-12-15
相关资源
相似解决方案