java实体转json

java实体转json

一、首先导入依赖:

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

二、其次

复制代码

Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("天津");

        //1、使用JSONObject
        JSONObject json = JSONObject.fromObject(stu);
        //2、使用JSONArray
        JSONArray array=JSONArray.fromObject(stu);

        String strJson=json.toString();
        String strArray=array.toString();

        System.out.println("strJson:"+strJson);
        System.out.println("strArray:"+strArray);

复制代码

三、Student实体

复制代码

 public static class Student{
        private String name;
        public String getName() { return name; }
        public void setName(String name) {
            this.name = name;
        }
        private String age;
        public String getAge() { return age; }
        public void setAge(String age) {
            this.age = age;
        }
        private String address;
        public String getAddress() { return address; }
        public void setAddress(String address) {
            this.address = address;
        }

    }

复制代码

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18561

发表评论