[JSON] JSON overview of similarities and differences between JSON and XML, JSON syntax, and Java JSON conversion

1. What is JSON?

JSON (JavaScript Object Notation, JS objects notation) is a lightweight data-interchange format. It is based on a subset of ECMAScript (European Computer Society norms established by js), using completely independent of the programming language of the text format to store and represent data. Simple and clear hierarchy make JSON an ideal data-interchange language. Easy to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.

  • Refers JSON JavaScript Object Notation (JavaScript Object Notation)
  • JSON is a lightweight data interchange format text
  • JSON is independent of language.
  • JSON self-descriptive better understood

JSON uses JavaScript syntax to describe data objects, but JSON is still independent of language and platform. JSON parser and JSON library supports many different programming languages. Currently a lot of dynamic (PHP, JSP, .NET) programming languages ​​support JSON.

2. XML and the similarities and differences

  • In common with XML
    1. JSON is a text
    2. JSON has "self-descriptive" (human readable)
    3. JSON has a hierarchical structure (in the presence of values)
    4. JSON can be parsed by JavaScript
    5. JSON data may be transmitted using AJAX
  • The difference with XML
    1. No end tag
    2. Shorter
    3. Faster read and write
    4. It can be built using JavaScript eval () methods to parse
    5. Using arrays
    6. Do not use a reserved word

3. Why JSON

For applications, AJAX, JSON faster and easier to use than XML:

  • Use XML
    to read XML documents
    using the XML DOM to loop through the document
    read value and stored in a variable
  • Use JSON
    read JSON string
    with eval () Processing JSON string

4. JSON syntax

4.1 Basic rules

  • Data in the name / value pairs: json data is composed of key-value pairs
    • Key marks (both odd and even lines) due to, quotes may not be used
    • Worth Value Type:
      1. number (integer or floating point)
      2. string (in double quotes)
      3. a logical value (true or to false)
      4. array (in square brackets) { "persons": [{ } {}]}
      5. objects (in braces) { "address": { " province": " Shaanxi" ...}}
      6. the null
    • Data separated by commas: a plurality of key-value pairs separated by a comma
    • Save Object braces: {} using the format defined json
    • Square brackets save array: []
<!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 data acquisition

  1. json object. keys
  2. json objects [ "key name"]
  3. Object array [index]
<!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. Traversal
<!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 conversion data and Java objects

  • JSON parser:
    • Common parser: Jsonlib, Gson, fastjson, jackson
  1. Introducing jar package related jackson
  2. Creating Jackson core object ObjectMapper
  3. ObjectMapper related method calls for conversion

5.1 Java objects into 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 object conversion 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);
    }
}
Published 412 original articles · won praise 135 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_41879343/article/details/104128318