• 使用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日--

  • 相关阅读:
    web项目优化
    mysql 优化笔记
    Java 调用 google 翻译
    Git回滚merge操作
    mybatis 批量插入 返回主键id
    idea tomcat debug 失效
    mysql 常用语句
    xstream 解析xml报文
    activeMQ 讲解及实战
    linux svn apache
  • 原文地址:https://www.cnblogs.com/heyang78/p/12442278.html
Copyright © 2020-2023  润新知