JSON 入门案例

1、json 是什么?

在这里插入图片描述

json 是一种轻量级的数据交换格式。

  • 轻量级是相对于 xml 而言的。
  • 数据交换指的是客户端和服务端之间业务数据的传递格式。

2、 json 在 javascript 中的应用:

2.1 json 的定义:

json 是由 键值对 组成,并且由花括号(大括号)包围,每个键用引号引起来,键值对之间用冒号进行分隔,多组键值对之间用逗号进行分隔。

 <script>
        let jsonObj ={
            "key1":12,
            "key2":"abc",
            "key3":true,
            "key4":[11,"arr",false],
            "key5":{
                "key5_1":551,
                "key5_2":"key5_2_value"
            },
            "key6":[
                    {"key6_1-1":6611,
                     "key6_1——2":"key_1_2_value"
                    },
                    {"key6_2-1":6622,
                     "key6_2——2":"key_2_2_value"
                    }
                ]
        };
        console.log(typeof jsonObj); // Object: json 就是一个对象
    </script>

2.2 json 的访问:

json 本身是一个对象,既然是对象, 那么 Json 中的每一个 key 都可以当做是 java 中对象的属性。

        // json 的访问:
        console.log(jsonObj.key1);

        console.log(jsonObj.key2);

        console.log(jsonObj.key3);

        for(let i = 0; i < jsonObj.key4.length; i ++) {
            console.log(jsonObj.key4[i]);
        }

        console.log(jsonObj.key5.key5_1);
        console.log(jsonObj.key5.key5_2);

        for(let i = 0; i < jsonObj.key6.length; i ++) {
            console.log(jsonObj.key6[i]);
        }

在这里插入图片描述

2.3 json 的两个常用方法:

json 的存在有两种表现形式:

  • 对象的形式存在 – json 对象。
  • 字符串的形式存在 – json 字符串。

一般我们要操作 json 中的数据的时候,需要 json 对象的格式。一般我们要在客户端和服务器之间进行数据交换的时候,使用json 字符串。.

JSON.stringify():
把json 对象转换为json 字符串。

        let jsonString = JSON.stringify(jsonObj);
        console.log(jsonString);

在这里插入图片描述

JSON.parse():
把json 字符串转换为json 对象。

        let jsonObject = JSON.parse(jsonString);
        console.log(jsonObject);

在这里插入图片描述

3、json 在 Java 中的使用:

环境搭建:

  • 添加 jar 包:

在这里插入图片描述

  • 创建实体类 Person:

    package entity;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    
    import java.util.Date;
    
    public class Person {
    
        private String name;
        private int age;
        private String gender;
         @JsonFormat(pattern = "yyyy-MM-dd")
        private Date birthday;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", gender='" + gender + '\'' +
                    '}';
        }
    }
    
    

3.1 java 对象转换为 json 字符串:

    /**
     *  Java 对象转换为 Json 字符串
     */
    @Test
    public void test1() {
        // 1.创建 Person 对象
        Person person = new Person();
        person.setName("张三");
        person.setAge(18);
        person.setGender("M");

        // 2.创建 Jackson 的核心对象 : ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        // 3.转换
        /**
         *  转换方法:
         *      writeValue(参数1,obj)
         *      参数1: File:将 obj 对象转换为 JSON 字符串,并保存到指定的文件中
         *        Writer: 将 obj 对象 转换为 JSON 字符串,并将json 字符串填充到 字符输出流中
         *        OutoutStream: 将 obj 对象转换为 JSON 字符串,并将 json 字符串填充到 字节输出流中
         *
         *      writeValueAsString(obj): 将对象转换为 json 字符串
         */
        String str = null;
        try {
            // 将对象转换为 json 字符串
            str = mapper.writeValueAsString(person);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        System.out.println(str); // {"name":"张三","age":18,"gender":"M"}

        try {
            // File:将 obj 对象转换为 JSON 字符串,并保存到指定的文件中
            mapper.writeValue(new File("d://a.txt"),person);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.2 @JsonIgnore & @JsonFormat 属性:

    @Test
    public void test2() {
        // 1.创建 Person 对象
        Person person = new Person();
        person.setName("张三");
        person.setAge(18);
        person.setGender("M");
        person.setBirthday(new Date());

        // 2.创建 Jackson 的核心对象 : ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        try {
            String s = mapper.writeValueAsString(person);
            /**
             *  {"name":"张三","age":18,"gender":"M","birthday":1598235179567}
             *  后面的 日期是 毫秒数,往往不是我们想要的结果:
             *  @JsonIgnore:忽略某个属性,注解在对象的属性或者get()方法上
             *  @JsonFormat: @JsonFormat(pattern = "yyyy-MM-dd") -- 会转换成指定的格式
             *  {"name":"张三","age":18,"gender":"M","birthday":"2020-08-24"}
             */
            System.out.println(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

3.3 List 集合转换为 json 字符串:

    @Test
    /**
     *  List 集合转换为 json 字符串
     */
    public void test3() throws JsonProcessingException {
        Person person1 = new Person();
        person1.setName("李四");
        person1.setAge(18);
        person1.setGender("M");
        person1.setBirthday(new Date());

        Person person2 = new Person();
        person2.setName("张三");
        person2.setAge(18);
        person2.setGender("M");
        person2.setBirthday(new Date());

        Person person3 = new Person();
        person3.setName("王五");
        person3.setAge(18);
        person3.setGender("M");
        person3.setBirthday(new Date());

        List<Person> ps = new ArrayList<Person>();
        ps.add(person1);
        ps.add(person2);
        ps.add(person3);

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(ps);
        System.out.println(s);
        //[
        //  {"name":"李四","age":18,"gender":"M","birthday":"2020-08-24"},
        //  {"name":"张三","age":18,"gender":"M","birthday":"2020-08-24"},
        //  {"name":"王五","age":18,"gender":"M","birthday":"2020-08-24"}
        // ]
    }

3.4 Map 集合转换为 json 字符串:

    @Test
    public void test4() throws JsonProcessingException {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name","田七");
        map.put("age",34);
        map.put("gender",'M');

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(map);
        System.out.println(s);
        //{"gender":"M","name":"田七","age":34}
    }

3.5 Json 字符串转换为 Java 对象:

    @Test
    /**
     *  Json 字符串转换为 Java 对象
     *  readValue(json字符串参数,class)
     */
    public void test5() throws JsonProcessingException {

        String json = "{\"name\":\"张三\",\"age\":\"18\",\"gender\":\"M\"}";

        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(json, Person.class);
        System.out.println(person);
        //Person{name='张三', age=18, gender='M'}
    }

4、总结:

以上就是 json 的基础内容,json 主要用于 前后台的数据的交互,本文还有很多不到位的地方,如有疑问,欢迎到下方留言。

如果文章对您有些许的帮助,动动小手,点赞哦。

Ajax入门案例

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乡野麦穗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值