JSON
一种轻量级的数据交换格式
格式: { “name” : “zhangsan” , “age” : “18”}
可以嵌套[]数组,{}对象如:
{
"num" : ["1","2","3",{
"n":"10",
"n1":"20"
} ]
}
使用方法
- 使用Gson
//创建Gson对象
Gson g = new Gson();
//创建书本对象
Book book = new Book("1","平凡的世界","你我皆平凡");
//对象转JSON
String s = g.toJson(book);
//s输出为:{"id":"1","name":"平凡的世界","info":"你我皆平凡"}
//json转对象,第二个参数为对象的Class
Book book1 = g.fromJson("{\"id\":\"1\",\"name\":\"平凡的世界\",\"info\":\"你我皆平凡\"}",Book.class);
- 使用fastjson
//直接转化json
String json = JSON.toJSONString(book);
//json转对象,第二个参数为对象的Class
Book b = JSON.parseObject("{\"id\":\"1\",\"name\":\"平凡的世界\",\"info\":\"你我皆平凡\"}",Book.class);
Gson的jar包下载:
https://search.maven.org/remotecontentfilepath=com/google/code/gson/gson/2.8.6/gson-2.8.6.jar
fastjson的jar包:https://search.maven.org/remote_contentg=com.alibaba&a=fastjson&v=LATEST