Json12_json1

1. 概念

  JavaScript Object Notation,也就是JavaScript对象表示法

  JavaScript用来表示对象的一种手段/方式。

  Person p = new Person();

  p.setName("zhangsan");

  p.setAge(23);

  p.setGender("男");

  这样使用Java语言的对象将这些零散的数据封装成了一个对象。将来用对象来当作参数来传递这些数据更加方便。

  JavaScript也想用对象来封装数据。提供了一种json的数据格式来封装数据。用json来表示对象被称为JavaScript对象表示法。

  JavaScript写法:var p = {"name":"zhangsan","age":23,"gender":"男"}; 这就称为json。

  * json现在多用于存储和交换文本信息的语法

  * 进行数据的传输

  * JSON比XML更小、更快,更易解析。

2. 语法

 JSON语法是JavaScript对象表示法语法的子集。

  a. 基本规则

    • 数据在名称/值对中:json数据是由键值对构成的
      • 键用引号(单双都行)引起来,也可以不使用引号
      • 值的取值类型:

          1、数字(整数或浮点数)

          2、字符串(在双引号中)

          3、逻辑值(true或false)

          4、数组(在方括号中)   {"persons":[{},{}]}

          5、对象(在花括号中)    {"address":{"province":"陕西"...}}

          6、null

    • 数据由逗号分隔:多个键值对由逗号分隔
    • 花括号保存对象:使用{}定义json格式
    • 方括号保存数组:[]

  代码1:值为数字、字符串、逻辑值

  json1.html

  var person = {"name":"张三",age:23,'gender':true};//最好不这么写,要么都加双引号,要么都加单引号,要么都不加引号

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true};
        alert(person);
    </script>
</head>
<body>

</body>
</html>

    浏览器访问http://localhost/day12/json1.html,检查结果:

    

  代码2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true};
        // alert(person);

        //2.嵌套格式{}->[]
        var persons = {
            "persons": [
                { "name": "张三", "age": 23, "gender": true },
                {"name": "李四","age": 24,"gender": true },
                { "name": "王五", "age": 25, "gender": false }
                ]
        };
        alert(persons);
    </script>
</head>
<body>

</body>
</html>

    浏览器访问http://localhost/day12/json1.html,检查结果同上。

  代码3:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true};
        // alert(person);

        //2.嵌套格式{}->[]
        var persons = {
            "persons": [
                { "name": "张三", "age": 23, "gender": true },
                {"name": "李四","age": 24,"gender": true },
                { "name": "王五", "age": 25, "gender": false }
                ]
        };
        // alert(persons);

        var ps = [
            { "name": "张三", "age": 23, "gender": true },
            {"name": "李四","age": 24,"gender": true },
            { "name": "王五", "age": 25, "gender": false }
        ];
        alert(ps);
    </script>
</head>
<body>

</body>
</html>

    浏览器访问http://localhost/day12/json1.html,检查结果:

    

  b. 获取数据

    1、json对象.键名

    2、json对象["键名"]

    3、数组对象[索引]:索引值从0开始

    4、遍历:获取json对象中所有的键和值

      • for(var key in json对象){ alert(key+":"+json对象[key]); }
      • for(var i = 0; i<json对象.length; i++){

          var p = json对象[i];

             for(var key in p){   alert(key + ":" + p[key]);   }

         }

  代码1:json1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true};
        // alert(person);
        //获取name的值
        var name1 = person.name;
        var name2 = person["name"];
        alert(name1+"------"+name2);

    </script>
</head>
<body>

</body>
</html>

    浏览器访问http://localhost/day12/json1.html,检查结果:

    

   代码2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        //2.嵌套格式{}->[]
        var persons = {
            "persons": [
                { "name": "张三", "age": 23, "gender": true },
                {"name": "李四","age": 24,"gender": true },
                { "name": "王五", "age": 25, "gender": false }
                ]
        };
        var name3 = persons.persons[2].name;
        alert(name3);
       
    </script>
</head>
<body>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        //2.嵌套格式{}->[]
        var ps = [
            { "name": "张三", "age": 23, "gender": true },
            {"name": "李四","age": 24,"gender": true },
            { "name": "王五", "age": 25, "gender": false }
        ];
        var name4 = ps[2].name;
        alert(name4);
    </script>
</head>
<body>

</body>
</html>

    以上两段代码,浏览器访问http://localhost/day12/json1.html,检查结果相同,如下:

    

   代码4:json2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //1.定义基本格式
        var person = { "name": "张三", "age": 23, "gender": true };

        //获取person对象中所有的键和值
        //for in 循环
        for(var key in person){
            //这样的方式获取不行,输出name:undefined,因为相当于person."name"
            // alert(key+":"+person.key);
            alert(key+":"+person[key]);
        }
    </script>
</head>
<body>

</body>
</html>

    浏览器访问http://localhost/day12/json2.html,检查结果:

    

     点击“确定”,检查结果:

    

    继续点击“确定”,检查结果:

    

   代码5:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        //嵌套格式{}->[]
        var ps = [
            { "name": "张三", "age": 23, "gender": true },
            {"name": "李四","age": 24,"gender": true },
            { "name": "王五", "age": 25, "gender": false }
        ];

        //获取ps中的所有值
        for(var i = 0; i<ps.length; i++){
            var p = ps[i];
            for(var key in p){
                alert(key + ":" + p[key]);
            }
        }
    </script>
</head>
<body>

</body>
</html>

    浏览器访问http://localhost/day12/json2.html,检查结果同上,第三次点击确定后,检查结果:

    

     继续点击“确定”,检查结果依次遍历

3. JSON数据和Java对象的相互转换

 JSON解析器:常见的解析器:Jsonlib,Gson,fastjson,jackson

  a. Java对象转成JSON

   使用步骤

    1、导入jackson的相关jar包

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

    3、调用ObjectMapper的相关方法进行转换

      3.1转换方法:

        i. void writeValue(参数1,obj):

          参数1: File:将obj对象转换为JSON字符串,并保存到指定的文件中

          Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中

          OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中

        ii. String writeValueAsString(obj):将对象转为json字符串

      3.2 注解:

        i. @JsonIgnore:排除属性

        ii. @JsonFormat:属性值的格式化(属性是Date类型) @JsonFormat(pattern = "yyyy-MM-dd") 

      3.3 复杂java对象转换

        i. List:转成了数组

        ii. Map:转成的格式跟对象格式一致

   代码1:Java对象转成JSON

package cn.itcast.domain;

import java.util.Date;

public class Person {

    private String name;
    private int age;
    private String gender;

    //alt+insert
    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;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}
package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;

public class JacksonTest {

    //Java对象转为json
    @Test
    public void test1() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");

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

        String json = mapper.writeValueAsString(p);
        System.out.println(json);
    }
}

    执行,检查结果:

    

    代码2:Java对象转成JSON

package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;

public class JacksonTest {

    //Java对象转为json
    @Test
    public void test1() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");

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

        //writeValue,将数据写道C://a.txt文件中
        mapper.writeValue(new File("c://a.txt"),p);

    }
}

    执行,检查结果:在C盘生成一个a.txt文件,文件中内容

    

     代码3:Java对象转成JSON

package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;

public class JacksonTest {

    //Java对象转为json
    @Test
    public void test1() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");

        //2.创建Jackson的核心对象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3.转换
        /*
            转换方法:
                writeValue(参数1, obj)
                    参数1:
                            File:将obj对象转换为JSON字符串,并保存到指定的文件中
                            Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                            OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
                writeValueAsString(obj):将对象转为json字符串
      */
        mapper.writeValue(new FileWriter("c://b.txt"),p);

    }
}

    执行,检查结果:在C盘生成一个b.txt文件,文件中内容同a.txt

   代码4:@JsonIgnore:排除/忽略属性

package cn.itcast.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
public class Person {

    private String name;
    private int age;
    @JsonIgnore //忽略该属性
    private String gender;

    //alt+insert
    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;
    }


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender +
                '}';
    }
}
package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;public class JacksonTest {

    @Test
    public void test2() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");

        //2. 转换
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(p);

        System.out.println(json);
    }
}

    执行,检查结果:

    

   代码5:@JsonFormat:属性值的格式化

package cn.itcast.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Person {

    private String name;
    private int age;
    private String gender;
    private Date birthday;

    //alt+insert
    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 + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}
package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.util.Date;

public class JacksonTest {

    @Test
    public void test2() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");
        p.setBirthday(new Date());

        //2. 转换
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(p);

        System.out.println(json);
    }
}

    执行,检查结果:

    

     这时候输出的生日直接看不懂,那么就需要格式化:

package cn.itcast.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Person {

    private String name;
    private int age;
    private String gender;

    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    //alt+insert
    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 + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}

    执行test2,检查结果:

    

   代码6:复杂java对象转换List:数组

package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JacksonTest {

    @Test
    public void test3() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");
        p.setBirthday(new Date());

        Person p1 = new Person();
        p1.setName("张三");
        p1.setAge(23);
        p1.setGender("男");
        p1.setBirthday(new Date());

        Person p2 = new Person();
        p2.setName("张三");
        p2.setAge(23);
        p2.setGender("男");
        p2.setBirthday(new Date());

        List<Person> ps = new ArrayList<>();
        ps.add(p);
        ps.add(p1);
        ps.add(p2);

        //2. 转换
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(ps);

        System.out.println(json);
    }
}

    执行test3,检查结果:

    

   代码7:复杂java对象转换Map:

package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class JacksonTest {

    @Test
    public void test4() throws Exception {
        //1.创建map对象
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age",23);
        map.put("gender","男");

        //2. 转换
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(map);

        System.out.println(json);
    }
}

    执行test4,检查结果:

    

  b. JSON转为Java对象

    1、导入jackson的相关jar包

    2、创建Jackson核心对象 ObjectMapper

    3、调用ObjectMapper的相关方法进行转换:readValue(json字符串数据,Class)

   代码1:

package cn.itcast.test;

import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class JacksonTest {

    //演示JSON字符串转为Java对象
    @Test
    public void test5() throws Exception {
        //1.初始化JSON字符串
        String json="{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}";
        //2. 创建ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper();
        //3.转换为Java对象 Person对象
        Person person = mapper.readValue(json, Person.class);
        System.out.println(person);
    }
}

    执行test5,检查结果:

    

 

posted on 2022-03-04 00:45  花溪月影  阅读(31)  评论(0编辑  收藏  举报