Java与JSON
做什么?
将Java中的对象 快速的转换为 JSON格式的字符串.
将JSON格式的字符串, 转换为Java的对象.
Gson
- 将对象转换为JSON字符串
转换JSON字符串的步骤:
1. 引入JAR包
2. 在需要转换JSON字符串的位置编写如下代码即可:
String json = new Gson().toJSON(要转换的对象);
案例:
Book b = BookDao.find();
String json = new Gson().toJson(b);
System.out.println(json);
- 将JSON字符串转换为对象
1. 引入JAR包
2. 在需要转换Java对象的位置, 编写如下代码:
对象 = new Gson().fromJson(JSON字符串,对象类型.class);
案例:
String json = "{\"id\":1,\"name\":\"金苹果\",\"author\":\"李伟\",\"info\":\"嘿嘿嘿嘿嘿嘿\",\"price\":198.0}";
Book book = new Gson().fromJson(json, Book.class);
System.out.println(book);
FastJson
- 将对象转换为JSON字符串
转换JSON字符串的步骤:
1. 引入JAR包
2. 在需要转换JSON字符串的位置编写如下代码即可:
String json=JSON.toJSONString(要转换的对象);
案例:
Book b = BookDao.find();
String json=JSON.toJSONString(b);
System.out.println(json);
- 将JSON字符串转换为对象
1. 引入JAR包
2. 在需要转换Java对象的位置, 编写如下代码:
类型 对象名=JSON.parseObject(JSON字符串, 类型.class);
或
List<类型> list=JSON.parseArray(JSON字符串,类型.class);
案例:
String json = "{\"id\":1,\"name\":\"金苹果\",\"author\":\"李伟杰\",\"info\":\"嘿嘿嘿嘿嘿嘿\",\"price\":198.0}";
Book book = JSON.parseObject(json, Book.class);
System.out.println(book);
- 具体代码如下:
- Gson
- Book类
public class Book {
private int id;
private String name;
private String info;
public Book(int id, String name, String info) {
this.id = id;
this.name = name;
this.info = info;
}
public Book() {
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", info='" + info + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return id == book.id && Objects.equals(name, book.name) && Objects.equals(info, book.info);
}
@Override
public int hashCode() {
return Objects.hash(id, name, info);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
主函数:转换为jeson格式
public static void main(String[] args) {
//创建Gson对象
Gson g =new Gson();
//转换
Book book = new Book(1001,"水浒传","武松打虎");
String s = g.toJson(book);
System.out.println(s);
}
jeson格式转换为字符串
public static void main(String[] args) {
//创建Gson对象
Gson g =new Gson();
//转换 {"id":1001,"name":"水浒传","info":"武松打虎"}
String json = "{\"id\":1001,\"name\":\"水浒传\",\"info\":\"武松打虎\"}";
Book book = g.fromJson(json,Book.class);
System.out.println(book.getName());
}
还要导相关的jar包
- FastJson
- 转换为JSON格式
public static void main(String[] args) {
Book book = new Book(1002,"西游记","唐僧拳打白骨精,脚踢南天门");
//1. 转换
String s = JSON.toJSONString(book);
System.out.println(s);
}
JSON转换为字符串
public static void main(String[] args) {
//1. 转换 {"id":1002,"info":"唐僧拳打白骨精,脚踢南天门","name":"西游记"}
Book book = JSON.parseObject("{\"id\":1002,\"info\":\"唐僧拳打白骨精,脚踢南天门\",\"name\":\"西游记\"}", Book.class);
System.out.println(book.getInfo());
}