当前位置:网站首页>数据交换 JSON
数据交换 JSON
2022-07-01 03:10:00 【Al_tair】
JSON
大家好呀,我是小笙,以下是我学习数据交换-JSON的学习笔记
数据交换 JSON
概述
JSON 指的是 JavaScript 对象表示法,也是轻量级的文本数据交换格式
JSON的定义格式
var 变量名 = {
"k1" : value, // Number 类型
"k2" : "value", // 字符串类型
"k3" : [], // 数组类型
"k4" : {
}, // json 对象类型
"k5" : [{
},{
}] // json 数组
};
代码示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json 快速入门案例</title>
<script type="text/javascript"> var myJson = {
"key1": "罗念笙", // 字符串 "key2": 123, // Number "key3": [1, "hello", 2.3], // 数组 "key4": {
"age": 12, "name": "jack"}, //json 对象 "key5": [ //json 数组 {
"k1": 10, "k2": "tom"}, {
"k3": 30, "k4": "smith"} ] , }; // 访问 json 的属性 console.log("key1= " + myJson.key1); // 罗念笙 console.log("key1= " + myJson.key2); // 123 // 访问 json 的数组属性 console.log("key3[1]= " + myJson.key3[1]); // hello // 访问 key4 的 name 属性 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 // 访问 key5 json 数组的第一个元素 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 快速入门案例</h1>
</body>
</html>
JSON 对象和字符串对象转换
- JSON.stringify(json)功能: 将一个 json 对象转换成为 json 字符串
- JSON.parse( jsonString )功能: 将一个 json 字符串转换成为 json 对象
代码示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON 对象和字符串对象转换</title>
<script type="text/javascript"> //JSON 是一个 build-in 对象,内置对象 console.log(JSON) // json 对象 var jsonObj = {
"name": "罗念笙","age": 18}; console.log("json 对象 " , jsonObj); // 把 json 对象转换成为字符串对象 var jsonStr = JSON.stringify(jsonObj); console.log("字符串: " + jsonStr); // 把 json 对象的字符串,转换成为 json 对象 var jsonObj2 = JSON.parse(jsonStr); console.log("json 对象 " , jsonObj2); </script>
</head>
<body>
<h1>JSON 对象和字符串对象转换</h1>
</body>
</html>
注意细节
在定义 Json 对象时, key值可以使用 ’ ’ 或者 " "表示字符串,甚至可以不用加引号
- var json_person = {“name”: “jack”, “age”: 100};
- var json_person = {‘name’: ’jack‘, ‘age’: 100};
- var json_person = {name: “jack”, age: 100};
但是把原生字符串转成 json 对象时, 必须使用 “”, 否则会报错
var str = "{\"name\": \"罗念笙\",\"age\": 18}" console.log("json 对象 " , JSON.parse(str));JSON.springify(json 对象) 返回的字符串, 都是 “” 表示的字符串, 是可以重新转成 json 对象
JSON 在 java 中使用
- java 中使用 json,需要引入的包 gson.jar
- Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库
- JSON 字符串 和 Java 对象之间相互转换

Javabean 对象和 json 字符串 的转换
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 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库
Gson gson = new Gson();
// 创建javabean对象
Book book = new Book(1, "红楼梦");
// Javabean 对象 => json 字符串
String s = gson.toJson(book);
System.out.println(s); // {"id":1,"name":"红楼梦"}
// json 字符串 => Javabean 对象
String str = "{\"id\": 2 , \"name\" : \"水浒传\" }";
Book book2 = gson.fromJson(str, Book.class);
System.out.println(book2); // Book{id=2, name='水浒传'}
}
}
List 对象和 json 字符串 的转换
public class LIstJson {
public static void main(String[] args) {
Gson gson = new Gson();
// List 对象和 json 字符串 的转换
List<Book> list = new ArrayList<>();
// 添加4本书
list.add(new Book(1,"红楼梦"));
list.add(new Book(2,"三国演义"));
list.add(new Book(3,"水浒传"));
list.add(new Book(4,"西游记"));
// List 对象 => json 字符串
String s = gson.toJson(list);
System.out.println(s);
// json 字符串 => List 对象
String listBook = "[{\"id\":1,\"name\":\"红楼梦\"},{\"id\":2,\"name\":\"三国演义\"}," +
"{\"id\":3,\"name\":\"水浒传\"},{\"id\":4,\"name\":\"西游记\"}]";
// TypeToken 是一个自定义泛型类,在创建时,需要指定具体类型,这里我们指定为 List<Book>
// type:java.util.List<com.al_tair.Book>
// 创建TypeToken<List<Book>>(){}匿名内部类,默认调用无参构造器中的super构造器,才可以访问受保护的TypeToken构造器
Type type = new TypeToken<List<Book>>(){
}.getType();
List<Book> listJson = gson.fromJson(listBook, type);
System.out.println(listJson);
}
}
map 对象和 json 字符串 的转换
public class MapJson {
public static void main(String[] args) {
Gson gson = new Gson();
// Map 对象和 json 字符串 的转换
Map<Integer,Book> map = new HashMap();
// 添加4本书
map.put(1,new Book(1,"红楼梦"));
map.put(2,new Book(2,"三国演义"));
map.put(3,new Book(3,"水浒传"));
map.put(4,new Book(4,"西游记"));
// Map 对象 => json 字符串
String s = gson.toJson(map);
System.out.println(s);
// json 字符串 => Map 对象
String mapBook = "{\"1\":{\"id\":1,\"name\":\"红楼梦\"},\"2\":{\"id\":" +
"2,\"name\":\"三国演义\"},\"3\":{\"id\":3,\"name\":\"水浒传\"},\"4\":{\"id\":4,\"name\":\"西游记\"}}";
Type type = new TypeToken<Map<Integer, Book>>() {
}.getType();
Map<Integer,Book> bookMap = gson.fromJson(mapBook, type);
System.out.println(bookMap);
}
}
边栏推荐
- Communication protocol -- Classification and characteristics Introduction
- HTB-Lame
- Redis 教程
- Depth first traversal of C implementation Diagram -- non recursive code
- POI exports excel and displays hierarchically according to parent-child nodes
- 伺服第二编码器数值链接到倍福PLC的NC虚拟轴做显示
- Clion and C language
- Summary of problems encountered in debugging positioning and navigation
- [reading notes] copywriting realization -- four golden steps for writing effective copywriting
- 8 pits of redis distributed lock
猜你喜欢
![Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]](/img/83/e3c9d8eda9d5351d4c54928d3b090b.png)
Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]

Hello World generation

Redis高效点赞与取消功能

EtherCAT原理概述

xxl-job使用指南
![[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)](/img/73/a22ab1dbb46e743ffd5f78b40e66a2.png)
[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
![[us match preparation] complete introduction to word editing formula](/img/e4/5ef19d52cc4ece518e79bf10667ef4.jpg)
[us match preparation] complete introduction to word editing formula

Network address translation (NAT) technology

Complete training and verification of a neural network based on pytorch

Metadata in NFT
随机推荐
多元线性回归
Const and the secret of pointers
lavaweb【初识后续问题的解决】
Redis分布式锁的8大坑
[exsi] transfer files between hosts
Druid monitoring statistics source
JS日常开发小技巧(持续更新)
岭回归和lasso回归
Add / delete / modify query summary insert/create/put/add/save/post, delete/drop/remove, update/modify/change, select/get/list/find
Is it safe to open an account online in a small securities firm? Will my money be unsafe?
xxl-job使用指南
Completely solve the lost connection to MySQL server at 'reading initial communication packet
Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
第03章_用户与权限管理
Scale SVG to container without mask / crop
Chapter 03_ User and authority management
Chapitre 03 Bar _ Gestion des utilisateurs et des droits
PHP batch Excel to word
[reading notes] copywriting realization -- four golden steps for writing effective copywriting