JSON 和 集合 互相转换(JSONObject和JSONArray使用)

转载

原文:https://www.cnblogs.com/520playboy/p/5766190.html

1.所依赖JAR包

要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:

commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar

  1. 应用场景:

后台的java类,如实体类、List、Set、Map转成json字符串发送到其它项目或者jsp端
jsp端或者其它项目发送过来的json字符串,需要解析成l实体类、List、Set、Map等java类

3.Demo

Student实体类

package json;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Student {
     private int id;
     private String name;
     private String age;
     private Date birthDay;
     private List list;
     private Set set;
     private Map map;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    
    public Date getBirthDay() {
        return birthDay;
    }
    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }
    
    public List getList() {
        return list;
    }
    public void setList(List list) {
        this.list = list;
    }
    public Set getSet() {
        return set;
    }
    public void setSet(Set set) {
        this.set = set;
    }
    
    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = map;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", birthDay=" + birthDay + ", list=" + list + ", set=" + set
                + ", map=" + map + "]";
    }
    
     
}

java对象序列化成json对象时,处理日期的处理类

package json;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/**
 * 
 * @author yangguojun
 * java实体类转jsonObject时,日期处理类
 */
public class JsonDateValueProcessor implements JsonValueProcessor {
     /**
      * 集合中实体类日期处理
      */
    @Override
    public Object processArrayValue(Object value , JsonConfig config) {
        // TODO Auto-generated method stub
        return processor(value);
    }
    /**
     * 当个实体类日期处理
     */
    @Override
    public Object processObjectValue(String propertyName, Object value, JsonConfig config) {
        return processor(value);
    }
    /**
     * 把日期对象转为字符串
     * @param value
     * @return
     */
    private Object processor(Object value){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(value instanceof Date){
            return format.format(value);
        }
        return value == null ? "":value.toString();        
    }

}

测试类

package json;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonDemo {
    public static void main(String[] args) {
        //创建JSON对象的第一种方法
        JSONObject jsonObj1 = new JSONObject();
        jsonObj1.put("id", "1");
        jsonObj1.put("name", "rose");
        jsonObj1.put("age", 25);
        System.out.println("jsonObj1"+jsonObj1);
        //创建JSON对象的第二种方法
        HashMap<String, Object> map = new HashMap<String,Object>();
        map.put("id", "2");
        map.put("name", "zhangsan");
        map.put("age", "25");
        JSONObject jsonObj2 = JSONObject.fromObject(map);
        System.out.println("jsonObj2"+jsonObj2);
        
         //创建一个JsonArray方法1
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0, "ZHULI");
        jsonArray.add(1, "30");
        jsonArray.add(2, "ALI");
        System.out.println("jsonArray1:" + jsonArray);
        
        //创建JsonArray方法2
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("柯文修");
        arrayList.add("23");
        arrayList.add("5");
        System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));
        
        //创建一个复杂JSON对象(JSON对象里有JSON数组)
        JSONObject jsonObj3 = new JSONObject();
        jsonObj3.put("id", 3);
        jsonObj3.put("name", "lisi");
        jsonObj3.put("age", 23);
        jsonObj3.put("arrayList", arrayList);
        System.out.println("jsonObj3"+jsonObj3);
        
        //创建一个复杂JSON数组(JSON数组里含有JSON对象)、
        JSONArray jsonArray3 = new JSONArray();
        jsonArray3.add("4");
        jsonArray3.add("wangwu");
        jsonArray3.add("26");
        jsonArray3.add(map);
        System.out.println("jsonArray3"+jsonArray3);       
        //把JSON字符串转为JSON对象
        String jsonString = "{\"id\":3,\"name\":\"lisi\",\"age\":23,\"arrayList\":[\"ZHULI\",\"30\",\"ALI\"]}";
        JSONObject jsonObj4 = JSONObject.fromObject(jsonString);
        System.out.println(jsonObj4.get("id")+"--"+jsonObj4.get("name")+"--"+jsonObj4.get("age")+
                "--"+jsonObj4.get("arrayList"));
        //java实体类转为JSONObject
        Student stu = new Student();
        stu.setId(1);
        stu.setName("罗志茂");
        stu.setAge("23");
        stu.setBirthDay(new Date());
        stu.setList(arrayList);
        HashSet<Object> set = new HashSet<>();
        set.add("6");
        set.add("戚广辉");
        set.add("25");
        stu.setSet(set);
        stu.setMap(map);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        JSONObject jsonObj5 = JSONObject.fromObject(stu,jsonConfig);
        System.out.println("序列化:"+jsonObj5);
        //json转java实体类
        Student student = (Student) JSONObject.toBean(jsonObj5, Student.class);
        System.out.println("反序列化:"+student);
       }
   
       
}

测试结果

jsonObj1{“id”:“1”,“name”:“rose”,“age”:25}
jsonObj2{“id”:“2”,“age”:“25”,“name”:“zhangsan”}
jsonArray1:[“ZHULI”,“30”,“ALI”]
jsonArray2:[“柯文修”,“23”,“5”]
jsonObj3{“id”:3,“name”:“lisi”,“age”:23,“arrayList”:[“柯文修”,“23”,“5”]}
jsonArray3[“4”,“wangwu”,“26”,{“id”:“2”,“age”:“25”,“name”:“zhangsan”}]
3–lisi–23–[“ZHULI”,“30”,“ALI”]
序列化:{“age”:“23”,“birthDay”:“2016-08-13 23:22:27”,“id”:1,“list”:[“柯文修”,“23”,“5”],“map”:{“id”:“2”,“age”:“25”,“name”:“zhangsan”},“name”:“罗志茂”,“set”: [“戚广辉”,“6”,“25”]}
反序列化:Student [id=1, name=罗志茂, age=23, birthDay=Sat Aug 13 23:22:27 CST 2016, list=[柯文修, 23, 5], set=[戚广辉, 6, 25], map={id=2, name=zhangsan, age=25}]

你可能感兴趣的:(JavaSE)