当前位置:网站首页>Data exchange JSON
Data exchange JSON
2022-07-01 03:19:00 【Al_ tair】
JSON
Hello, everyone , I'm Xiao Sheng , The following is my study of data exchange -JSON Learning notes of
Data exchange JSON
summary
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

<!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

<!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

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);
}
}
边栏推荐
- 伺服第二编码器数值链接到倍福PLC的NC虚拟轴做显示
- ECMAScript 6.0
- Keil5中如何做到 0 Error(s), 0 Warning(s).
- Design practice of current limiting components
- C language EXECL function
- go实现命令行的工具cli
- STM32 - DS18B20 temperature sampling of first-line protocol
- Subnet division and subnet summary
- 8 pits of redis distributed lock
- Cloud native annual technology inventory is released! Ride the wind and waves at the right time
猜你喜欢

VMware vSphere 6.7虚拟化云管理之12、VCSA6.7更新vCenter Server许可

Redis tutorial

Multithreaded printing
性能测试常见面试题

STM32 - DS18B20 temperature sampling of first-line protocol

Introduction and basic knowledge of machine learning
![[us match preparation] complete introduction to word editing formula](/img/e4/5ef19d52cc4ece518e79bf10667ef4.jpg)
[us match preparation] complete introduction to word editing formula

EtherCAT原理概述

Depth first traversal of C implementation Diagram -- non recursive code

How do spark tasks of 10W workers run? (Distributed Computing)
随机推荐
一文讲解发布者订阅者模式与观察者模式
Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
About the application of MySQL
Servlet [first introduction]
POI导出excel,按照父子节点进行分级显示
CX5120控制汇川IS620N伺服报错E15解决方案
Redis分布式锁的8大坑
[applet project development -- JD mall] uni app commodity classification page (Part 2)
Druid monitoring statistics source
如何校验两个文件内容是否相同
雪崩问题以及sentinel的使用
[us match preparation] complete introduction to word editing formula
shell脚本使用两个横杠接收外部参数
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
Redis tutorial
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
Depth first traversal of C implementation Diagram -- non recursive code
How do spark tasks of 10W workers run? (Distributed Computing)
Magnetic manometer and measurement of foreign coins