使用Json-lib将对象和Json互转

工程下载地址: https://files.cnblogs.com/files/xiandedanteng/jsonSample20200308.rar

Depenency:

        <!-- 使用json-lib -->
        <dependency>    
            <groupId>net.sf.json-lib</groupId>    
            <artifactId>json-lib</artifactId>    
            <version>2.4</version>    
            <classifier>jdk15</classifier>    
        </dependency>

代码:

        // 对象到文本
        Emp emp=new Emp();
        emp.setId(1001);
        emp.setName("苗婉秋");
        emp.setSalary(1000);
        
        JSONObject jsonObject = JSONObject.fromObject(emp);
        System.out.println("emp对象的json文本=" + jsonObject);
        
        // 文本到对象
        String jsonStr = "{"id":1001,"name":"苗婉秋","salary":1000}";
        JSONObject jsonObject1 = JSONObject.fromObject(jsonStr);

        Emp emp2 = (Emp) JSONObject.toBean(jsonObject1,Emp.class);
        System.out.println(emp2);

输出:

emp对象的json文本={"id":1001,"name":"苗婉秋","salary":1000}
emp:1001,苗婉秋,1000

使用到的Emp对象

package jsonSample;

public class Emp {
    private long id;
    private String name;
    private int salary;
    
    public String toString() {
        return String.format("emp:%d,%s,%d",id,name,salary);
    }
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }

}

 参考资料:https://www.cnblogs.com/nananana/p/9263708.html

--2020年3月8日--

原文地址:https://www.cnblogs.com/heyang78/p/12442278.html