当前位置:网站首页>Data exchange JSON

Data exchange JSON

2022-07-01 03:19:00 Al_ tair

Hello, everyone , I'm Xiao Sheng , The following is my study of data exchange -JSON Learning notes of

Data exchange JSON

summary

json Online document

JSON refer to JavaScript Object notation , It is also a lightweight text data exchange format

JSON The definition format of

var  Variable name  = {
     
    "k1" : value, // Number  type  
    "k2" : "value", //  String type 
    "k3" : [], //  An array type  
    "k4" : {
    }, // json  object type  
    "k5" : [{
    },{
    }] // json  Array  
};

Code example

image-20220511113607261

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>json  Quick start case </title>
		<script type="text/javascript"> var myJson = {
       "key1": " Niansheng ", //  character string   "key2": 123, // Number  "key3": [1, "hello", 2.3], //  Array   "key4": {
      "age": 12, "name": "jack"}, //json  object   "key5": [ //json  Array   {
      "k1": 10, "k2": "tom"}, {
      "k3": 30, "k4": "smith"} ] , }; //  visit  json  Properties of   console.log("key1= " + myJson.key1); //  Niansheng  console.log("key1= " + myJson.key2); // 123 //  visit  json  Array properties for   console.log("key3[1]= " + myJson.key3[1]); // hello //  visit  key4  Of  name  attribute   console.log("name= " , myJson.key4); // name= {age: 12, name: 'jack'} console.log("name= " + myJson.key4); // name= [object Object] console.log("name= " + myJson.key4.name); // jack //  visit  key5 json  The first element of the array   console.log("myJson.key5[0]= " + myJson.key5[0]); //[object, object]  console.log("myJson.key5[0].k2= " + myJson.key5[0].k2) // tom </script>
	</head>
	<body>
		<h1>json  Quick start case </h1>
	</body>
</html>

JSON Object and string object conversion

  • JSON.stringify(json) function : Will a json Object converted to json character string
  • JSON.parse( jsonString ) function : Will a json String conversion to json object

Code example

image-20220511115229117

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>JSON  Object and string object conversion </title>
		<script type="text/javascript"> //JSON  It's a  build-in  object , Built-in objects  console.log(JSON) // json  object   var jsonObj = {
      "name": " Niansheng ","age": 18}; console.log("json  object  " , jsonObj); //  hold  json  Object is converted to a string object   var jsonStr = JSON.stringify(jsonObj); console.log(" character string : " + jsonStr); //  hold  json  Object's string , Convert into  json  object   var jsonObj2 = JSON.parse(jsonStr); console.log("json  object  " , jsonObj2); </script>
	</head>
	<body>
		<h1>JSON  Object and string object conversion </h1>
	</body>
</html>

Attention to detail

  • In defining Json Object time , key Value can be used ’ ’ perhaps " " Representation string , Even without quotes

    • var json_person = {“name”: “jack”, “age”: 100};
    • var json_person = {‘name’: ’jack‘, ‘age’: 100};
    • var json_person = {name: “jack”, age: 100};
  • But convert the native string to json Object time , You have to use “”, Otherwise, an error will be reported

    var str = "{\"name\": \" Niansheng \",\"age\": 18}"
    console.log("json  object  " , JSON.parse(str)); 
    
  • JSON.springify(json object ) String returned , All are “” String represented , Yes, it can be converted into json object

JSON stay java Use in

  • java Use in json, Packages that need to be introduced gson.jar
  • Gson yes Google What is provided is used in Java Objects and JSON Mapping between data Java Class library
  • JSON character string and Java Objects are converted to each other

image-20220511131709778

Javabean Objects and json character string Transformation

JavaBean

public class Book {
    
    private Integer id;
    private String name;

    public Book() {
    
    }

    public Book(Integer id, String name) {
    
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
    
        return id;
    }

    public void setId(Integer id) {
    
        this.id = id;
    }

    public String getName() {
    
        return name;
    }

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

    @Override
    public String toString() {
    
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
public class JavaJson {
    
    public static void main(String[] args) {
    
        // Gson  yes  Google  What is provided is used in  Java  Objects and  JSON  Mapping between data  Java  Class library 
        Gson gson = new Gson();
        //  establish javabean object 
        Book book = new Book(1, " A dream of red mansions ");
        // Javabean  object  => json  character string 
        String s = gson.toJson(book);
        System.out.println(s); // {"id":1,"name":" A dream of red mansions "}
        // json  character string  => Javabean  object 
        String str = "{\"id\": 2 , \"name\" : \" Water margin \" }";
        Book book2 = gson.fromJson(str, Book.class);
        System.out.println(book2); // Book{id=2, name=' Water margin '}
    }
}

List Objects and json character string Transformation

public class LIstJson {
    
    public static void main(String[] args) {
    
        Gson gson = new Gson();
        // List  Objects and  json  character string   Transformation 
        List<Book> list = new ArrayList<>();
        //  add to 4 This book 
        list.add(new Book(1," A dream of red mansions "));
        list.add(new Book(2," The romance of The Three Kingdoms "));
        list.add(new Book(3," Water margin "));
        list.add(new Book(4," Journey to the west "));

        // List  object  => json  character string 
        String s = gson.toJson(list);
        System.out.println(s);

        // json  character string  => List  object 
        String listBook = "[{\"id\":1,\"name\":\" A dream of red mansions \"},{\"id\":2,\"name\":\" The romance of The Three Kingdoms \"}," +
            "{\"id\":3,\"name\":\" Water margin \"},{\"id\":4,\"name\":\" Journey to the west \"}]";
        // TypeToken  Is a custom generic class , When creating a , You need to specify a specific type , Here we designate as  List<Book>
        // type:java.util.List<com.al_tair.Book>
        //  establish TypeToken<List<Book>>(){} Anonymous inner class , The default call is... In the parameterless constructor super Constructors , To access protected TypeToken Constructors 
        Type type = new TypeToken<List<Book>>(){
    }.getType();
        List<Book> listJson = gson.fromJson(listBook, type);
        System.out.println(listJson);
    }
}

map Objects and json character string Transformation

public class MapJson {
    
    public static void main(String[] args) {
    
        Gson gson = new Gson();
        // Map  Objects and  json  character string   Transformation 
        Map<Integer,Book> map = new HashMap();
        //  add to 4 This book 
        map.put(1,new Book(1," A dream of red mansions "));
        map.put(2,new Book(2," The romance of The Three Kingdoms "));
        map.put(3,new Book(3," Water margin "));
        map.put(4,new Book(4," Journey to the west "));

        // Map  object  => json  character string 
        String s = gson.toJson(map);
        System.out.println(s);

        // json  character string  => Map  object 
        String mapBook = "{\"1\":{\"id\":1,\"name\":\" A dream of red mansions \"},\"2\":{\"id\":" +
            "2,\"name\":\" The romance of The Three Kingdoms \"},\"3\":{\"id\":3,\"name\":\" Water margin \"},\"4\":{\"id\":4,\"name\":\" Journey to the west \"}}";

        Type type = new TypeToken<Map<Integer, Book>>() {
    }.getType();
        Map<Integer,Book> bookMap = gson.fromJson(mapBook, type);
        System.out.println(bookMap);
    }
}
原网站

版权声明
本文为[Al_ tair]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010310248450.html