当前位置:网站首页>数据交换 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);
}
}
边栏推荐
- Is it safe to open an account online in a small securities firm? Will my money be unsafe?
- 力扣-两数之和
- A few lines of transaction codes cost me 160000 yuan
- Promise中finally的用法
- Chapter 03_ User and authority management
- Latest interface automation interview questions
- Overview of EtherCAT principle
- Chapitre 03 Bar _ Gestion des utilisateurs et des droits
- 【小程序项目开发-- 京东商城】uni-app之分类导航区域
- Multithreaded printing
猜你喜欢

php批量excel转word

Completely solve the lost connection to MySQL server at 'reading initial communication packet

Elk elegant management server log

彻底解决Lost connection to MySQL server at ‘reading initial communication packet

STM32——一线协议之DS18B20温度采样

Overview of EtherCAT principle

咱就是说 随便整几千个表情包为我所用一下

世界上最好的学习法:费曼学习法

Redis tutorial

Edge Drawing: A combined real-time edge and segment detector 翻译
随机推荐
STM32——一线协议之DS18B20温度采样
Druid monitoring statistics source
性能测试常见面试题
Edge Drawing: A combined real-time edge and segment detector 翻译
Analyze datahub, a new generation metadata platform of 4.7K star
数组的includes( )
Completely solve the lost connection to MySQL server at 'reading initial communication packet
Let's just say I can use thousands of expression packs
一文讲解发布者订阅者模式与观察者模式
Best used trust automation script (shell)
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
Stop saying that you can't solve the "cross domain" problem
A few lines of transaction codes cost me 160000 yuan
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
如果在小券商办理网上开户安全吗?我的资金会不会不安全?
Introduction to core functions of webrtc -- an article on understanding SDP PlanB unifiedplan (migrating from PlanB to unifiedplan)
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
The 'mental (tiring) process' of building kubernetes/kubesphere environment with kubekey
Introduction to EtherCAT
E15 solution for cx5120 controlling Huichuan is620n servo error