JSON
1、简介
JSON : JavaScript Object Notation
2、对象格式
一本书
书名
作者
出版社
2.1、java
//java
public class Book{
private String name;
private String writer;
private String publisher;
}
Book book = new Book();
book.setName("我是书名");
book.setWriter("我是作者");
book.setPublisher("我是出版社");
2.2 、javascript
//javascript
var book = new Object();
book.name = "我是书名";
book.writer = "我是作者";
book.publisher = "我是出版社";
2.3、XML
<books>
<book>
<name>"我是书名"</name>
<writer>"我是作者"</writer>
<publisher>"我是出版社"</publisher>
</book>
</books>
2.4、JSON
{
"name":"我是书名",
"writer" : "我是作者",
"publisher" : "我是出版社"
}
3、Java与JSON
3.1、Java与JSON能做什么
- 将java中的对象转换成JSON格式的字符串
- 将JSON的字符串转换成为Java对象
3.2、Gson
- 将java中的对象转换成JSON格式的字符串
import com.google.gson.Gson;
public class GaonJava2Json {
public static void main(String[] args) {
Book book = new Book("我是书","我是作者","我是出版社");
Gson gson = new Gson();
String bookJson = gson.toJson(book);
System.out.println(bookJson);
//{"name":"我是书","writer":"我是作者","publisher":"我是出版社"}
}
}
- 将JSON的字符串转换成为Java对象
import com.google.gson.Gson;
public class GsonJson2Java {
public static void main(String[] args) {
String str =
"{\"name\":\"我是书\",\"writer\":\"我是作者\",\"publisher\":\"我是出版社\"}";
Gson gson = new Gson();
Book book = gson.fromJson(str, Book.class);
System.out.println(book);
//Book{name='我是书', writer='我是作者', publisher='我是出版社'}
}
}
3.3、FastJson
- 将java中的对象转换成JSON格式的字符串
import com.alibaba.fastjson.JSON;
public class FastJsonJava2Json {
public static void main(String[] args) {
Book book = new Book("我是书","我是作者","我是出版社");
String jsonString = JSON.toJSONString(book);
System.out.println(jsonString);
//{"name":"我是书","publisher":"我是出版社","writer":"我是作者"}
}
}
- 将JSON的字符串转换成为Java对象
import com.alibaba.fastjson.JSON;
public class FastJsonJson2Java {
public static void main(String[] args) {
String str =
"{\"name\":\"我是书\",\"writer\":\"我是作者\",\"publisher\":\"我是出版社\"}";
Book book = JSON.parseObject(str, Book.class);
System.out.println(book);
//Book{name='我是书', writer='我是作者', publisher='我是出版社'}
}
}