【JSON】JSON概述,JSON与XML的异同,JSON语法,JSON与Java的相互转换

1. 什么是JSON?

JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

  • JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
  • JSON 是轻量级的文本数据交换格式
  • JSON 独立于语言。
  • JSON 具有自我描述性,更易理解

JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。

2. 与XML的异同

  • 与 XML 相同之处
    1. JSON 是纯文本
    2. JSON 具有"自我描述性"(人类可读)
    3. JSON 具有层级结构(值中存在值)
    4. JSON 可通过 JavaScript 进行解析
    5. JSON 数据可使用 AJAX 进行传输
  • 与 XML 不同之处
    1. 没有结束标签
    2. 更短
    3. 读写的速度更快
    4. 能够使用内建的 JavaScript eval() 方法进行解析
    5. 使用数组
    6. 不使用保留字

3. 为什么使用JSON

对于 AJAX 应用程序来说,JSON 比 XML 更快更易使用:

  • 使用 XML
    读取 XML 文档
    使用 XML DOM 来循环遍历文档
    读取值并存储在变量中
  • 使用 JSON
    读取 JSON 字符串
    用 eval() 处理 JSON 字符串

4. JSON语法

4.1 基本规则

  • 数据在名称/值对中:json数据是由键值对构成的
    • 键用引号(单双都行)引起来,也可以不使用引号
    • 值得取值类型:
      1. 数字(整数或浮点数)
      2. 字符串(在双引号中)
      3. 逻辑值(true 或 false)
      4. 数组(在方括号中) {“persons”:[{},{}]}
      5. 对象(在花括号中) {“address”:{“province”:“陕西”…}}
      6. null
    • 数据由逗号分隔:多个键值对由逗号分隔
    • 花括号保存对象:使用{}定义json 格式
    • 方括号保存数组:[]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json数据语法</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true}
        alert(person)
        //2.嵌套格式 {}->[]
        var persons = {
            "person":[
                {"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>

4.2 获取数据

  1. json对象.键名
  2. json对象[“键名”]
  3. 数组对象[索引]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json数据语法</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true}
        alert(person)
        //获取name的值
        var name = person.name;
        var name = person["name"];
        alert(name);

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

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

</body>
</html>
  1. 遍历
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json数据语法</title>
    <script>
        //1.定义基本格式
        var person = {"name":"张三",age:23,'gender':true}
        //嵌套格式 []->{}
        var ps = [
            {"name":"张三","age":23,"gender":true},
            {"name":"李四","age":24,"gender":true},
            {"name":"王五","age":25,"gender":false}
            ];
        //获取person对象中所有的键和值
        //for in 循环
        for(var key in person){
            //这样的方式获取不行,因为相当于person."name"
            // alert(key + ":" + person.key);
            alert(key + ":" + person[key]);
        }
        //获取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>

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

  • JSON解析器:
    • 常见的解析器:Jsonlib,Gson,fastjson,jackson
  1. 导入jackson的相关jar包
  2. 创建Jackson核心对象 ObjectMapper
  3. 调用ObjectMapper的相关方法进行转换

5.1 Java对象转换JSON

ObjectMapper 转换方法:
       writeValue(参数1,obj):
           参数1:
               File:将obj对象转换为JSON字符串,并保存到指定的文件中
               Writer:将obj对象转换成JSON字符串,并将JSON数据填充到字符输出流中
               OutputStream:将obj对象转换成JSON字符串,并将JSON数据填充到字节输出流中
       writeValueAsString(obj):将对象转为json字符串
package cn.siyi.test;

import cn.siyi.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class JacksonTest {
    //Java对象转为JSON字符串
    @Test
    public void test1() throws IOException {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");

        //2.创建Jackson的核心对象 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        //3.转换
//        String json = objectMapper.writeValueAsString(p);
//        System.out.println(json);
//        objectMapper.writeValue(new File("D://a.txt"),p);
        objectMapper.writeValue(new FileWriter("d://b.txt"),p);
    }

    @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 objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(p);
        System.out.println(json);
    }

    @Test
    public void test03() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("李四");
        p.setAge(21);
        p.setGender("男");
        p.setBirthday(new Date());

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

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

        //创建List集合
        List<Person> ps = new ArrayList<Person>();
        ps.add(p);
        ps.add(p1);
        ps.add(p2);

        //转换
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(ps);
        System.out.println(json);
    }

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

        //转换
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(map);
        System.out.println(json);
    }
}

5.2 JSON对象转换Java

readValue(json字符串数据,Class)
package cn.siyi.test;

import cn.siyi.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class JacksonTest {
    //json字符串转为Java对象
    @Test
    public void test05() throws Exception {
        //1.初始化JSON字符串
        String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}";
        //2.创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(json, Person.class);
        System.out.println(person);
    }
}
发布了412 篇原创文章 · 获赞 135 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41879343/article/details/104128318