Java Web 之简单的生成JSON

本文详细介绍在JavaWeb中生成JSON的方法,包括使用JSONObject和JSONArray的基本操作,以及如何处理复杂的数据结构如实体类。同时介绍了序列化的概念及其在JSON生成中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON的生成


前言

本人学生一枚,正在学习Java Web,若文章中有错误,希望大佬能指出。

介绍

本篇文章主要介绍在Java Web中,怎么生成Json对象,当然本篇技术不是最方便,而是比写字符串稍微简单一点的技术,适合入门学习,若想使用更方便的技术,请学习有关JSON的框架。


代码体现和解释

1. 下载有关的jar包,若想方便可以点击这里

2. JSONObject和JSONArray(代码的作用都在注释里面)

public static void main(String[] args) {
        
        // 创建JSONObject第一种方法
        JSONObject jsonObjectOne = new JSONObject();
        jsonObjectOne.put("num", 1);
        jsonObjectOne.put("name", "WangXiaoNao");
        System.out.println("jsonObjectOne = " + jsonObjectOne);

        System.out.println("===============================================");

        // 创建JSONObject第二种方法
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name", "admin");
        hashMap.put("pwd", "123456");
        System.out.println("hashMap = " + hashMap);

        System.out.println("===============================================");


        // 创建JSONArray第一种方法

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0, "WangXiaoNao");
        jsonArray.add(1, "man");
        jsonArray.add(2, "20");
        System.out.println("jsonArray1 = " + jsonArray);
        System.out.println("===============================================");


        // 创建JSONArray第二种方法
        List<String> arrayList = new ArrayList<>();
        arrayList.add("WangXiaoNao");
        arrayList.add("20");
        // fromObject()方法:从其它对象转化成JSON对象
        System.out.println("jsonArray2 = " + JSONArray.fromObject(arrayList));
        //如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中
        System.out.println("jsonArray FROM HashMap = " + JSONArray.fromObject(hashMap));

        System.out.println("===============================================");


        //组装一个复杂的JSONArray
        JSONObject jsonObjectTwo = new JSONObject();
        jsonObjectTwo.put("username", "WangXiaoNao");
        jsonObjectTwo.put("age", "20");
        jsonObjectTwo.element("Array", arrayList);
        System.out.println("jsonObjectTwo = " + jsonObjectTwo);
        System.out.println("===============================================");


        // 解析JSON字符串
        String jsonString = "{\"name\":\"WangXiaoNao\",\"age\":\"20\",\"work\":\"Student\",\"Array\":[\"admin\",\"20\",\"teacher\"]}";
        System.out.println(jsonString);

        // 将JSON字符串转为Java对象
        JSONObject object = JSONObject.fromObject(jsonString);
        // 获取object中的name
        if (object.has("name")) {
            System.out.println("name = " + object.getString("name"));

        }

        // 获取Array
        if (object.has("Array")) {
            JSONArray array = object.getJSONArray("Array");
            for (int i = 0; i < array.size(); i++) {
                System.out.println("Array = " + array.getString(i) + " ");
            }
        }


    }
复制代码

运行结果:


注意:如果遇到下面的错误,说明你导入的commons-collections-3.2.2.jar版本号不对应,请到官网进行下载


3. 生成复杂的JSON数据

实体类

  • Student
public class Student implements Serializable {

    private int id;
    private String name;
    private Date birthday;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
复制代码
  • Teacher
public class Teacher implements Serializable {

    private String name;
    private String jabNum;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJabNum() {
        return jabNum;
    }

    public void setJabNum(String jabNum) {
        this.jabNum = jabNum;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", jabNum='" + jabNum + '\'' +
                '}';
    }
}

复制代码
  • ClassInfo
public class ClassInfo implements Serializable {

    private String className;
    private int classNum;
    private Teacher teacher;
    private List<Student> students = new ArrayList<>();

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public int getClassNum() {
        return classNum;
    }

    public void setClassNum(int classNum) {
        this.classNum = classNum;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "ClassInfo{" +
                "className='" + className + '\'' +
                ", classNum=" + classNum +
                ", teacher=" + teacher +
                ", students=" + students +
                '}';
    }
}
复制代码

主函数:

public static void main(String[] args) {

        Student student1 = new Student();
        student1.setId(1);
        student1.setName("WangXiaoNao");
        student1.setBirthday(new Date());


        JSONObject jsonObject = JSONObject.fromObject(student1);
        String s1 = jsonObject.toString();
        System.out.println("(默认日期)简单Bean转化为Json = " + s1);
        //(默认日期)简单Bean转化为Json = {"birthday":{"date":10,"day":6,"hours":15,"minutes":59,"month":2,"seconds":14,"time":1520668754290,"timezoneOffset":-480,"year":118},"id":1,"name":"WangXiaoNao"}

        System.out.println("======================================================");

        JSONObject jsonObject1 = JSONObject.fromObject(student1, getConfig());
        s1 = jsonObject1.toString();
        System.out.println("(设置日期)简单Bean转化为Json = " + s1);
        // (设置日期)简单Bean转化为Json = {"birthday":"2018-03-10 16:01:51.863","id":1,"name":"WangXiaoNao"}
        System.out.println("======================================================");


        // json转为简单的Bean
        JSONObject jsonObject2 = (JSONObject) JSONSerializer.toJSON(s1);
        Student student = (Student) JSONObject.toBean(jsonObject2, Student.class);
        System.out.println("Json转为简单Bean = " + student);
        // Json转为简单Bean = Student{id=1, name='WangXiaoNao', birthday=Sat Mar 10 16:04:28 CST 2018}
        System.out.println("======================================================");


        Student student2 = new Student();
        student2.setId(1);
        student2.setName("路人甲");
        student2.setBirthday(new Date());

        Student student3 = new Student();
        student3.setId(2);
        student3.setName("路人乙");
        student3.setBirthday(new Date());


        List<Student> students = new ArrayList<>();
        students.add(student);
        students.add(student2);
        students.add(student3);

        System.out.println("=============带泛型的List之间的转化=============");
        JSONArray jsonArray = JSONArray.fromObject(students, getConfig());
        // 带泛型的list转化为json
        String s = jsonArray.toString();
        System.out.println("带泛型的list转化为json = " + s);
        // 带泛型的list转化为json = [{"birthday":"2018-03-10 16:08:24.385","id":1,"name":"WangXiaoNao"},{"birthday":"2018-03-10 16:08:24.393","id":1,"name":"路人甲"},{"birthday":"2018-03-10 16:08:24.393","id":2,"name":"路人乙"}]

        // json转为带泛型的List
        // 数组
        Student[] students1 = (Student[]) JSONArray.toArray(jsonArray, Student.class);

        // 集合
        List<Student> studentList = JSONArray.toList(jsonArray, Student.class);
        for (Student stu : students1) {
            System.out.println("数组 : id =  " + stu.getId() + " name = " + stu.getName() + "Birthday = " + stu.getBirthday());

        }
        for (Student stu : studentList) {
            System.out.println("集合 : id =  " + stu.getId() + " name = " + stu.getName() + "Birthday = " + stu.getBirthday());


        }


        Teacher t = new Teacher();
        t.setJabNum("t101");
        t.setName("lijun");
        ClassInfo ci = new ClassInfo();
        ci.setClassName("cna");
        ci.setClassNum(101);
        ci.setStudents(students);
        ci.setTeacher(t);
        JSONObject clajso = JSONObject.fromObject(ci, getConfig());
        String c = clajso.toString();
        System.out.println("ci to json  //////////////");
        System.out.println(c);

        System.out.println("json to ci //////////");
        JSONObject o2 = (JSONObject) JSONSerializer.toJSON(c);
        ClassInfo cijson = (ClassInfo) JSONObject.toBean(o2, ClassInfo.class);
        JSONArray array = o2.getJSONArray("students");
        System.out.println(array.size());
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);
            Student studentaa = (Student) JSONObject.toBean(object,
                    Student.class);
            cijson.getStudents().add(studentaa);
        }
        System.out.println(cijson);


    }

    public static JsonConfig getConfig() {
        // 设置日期格式
        JsonConfig config = new JsonConfig();
        // 防止对象间的循环引用所产生的jsonString
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {

            public Object processObjectValue(String arg0, Object arg1,
                                             JsonConfig arg2) {
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                Date d = (Date) arg1;
                return sdf.format(d);
            }

            public Object processArrayValue(Object arg0, JsonConfig arg1) {
                // TODO Auto-generated method stub
                return null;
            }
        });
        return config;
    }
复制代码

4. 这里有很多人不明白为什么每个实体类要实现Serializable

序列化

  • 序列化:对象的寿命通常随着生成该对象的程序的终止而终止,有时候需要把在内存中的各种对象的状态(也就是实例变量,不是方法)保存下来,并且可以在需要时再将对象恢复。虽然你可以用你自己的各种各样的方法来保存对象的状态,但是Java给你提供一种应该比你自己的好的保存对象状态的机制,那就是序列化。

  • 总结:Java 序列化技术可以使你将一个对象的状态写入一个Byte 流里(系列化),并且可以从其它地方把该Byte 流里的数据读出来(反序列化)。

序列化的用途

  • 想把的内存中的对象状态保存到一个文件中或者数据库中时候

  • 想把对象通过网络进行传播的时候

如何序列化

  • 只要一个类实现Serializable接口,那么这个类就可以序列化了。例如实体类中的Student、Teacher、ClassInfo这些类都实现了序列化。

5. 总结

第一次写文章,难免会出现纰漏错误,如果您看到这些纰漏错误或者是有更好的方法,希望您能指出,将不胜感激。


转载于:https://juejin.im/post/5aa3a08c51882555642ba8a8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值