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);
将JSN字符串转换为对象
1. 引入JAR包
2. 在需要转换Java对象的位置, 编写如下代码:
对象 = new Gson().fromJson(JSON字符串,对象类型.class);
案例:String json = "{\"id\":1,\"name\":\"Ocean\",\"author\":\"呵呵呵 \",\"info\":\"live universe\",\"price\":19.98}";
Book book = new Gson().fromJson(json, Book.class);
System.out.println(book);
package com;
import com.google.gson.Gson;
import java.util.Objects;
public class book {
private String id;
@Override
public String toString() {
return "book{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", info='" + info + '\'' +
'}';
}
private String name;
private String info;
public book(String id, String name, String info) {
this.id = id;
this.name = name;
this.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 Objects.equals(id, book.id) &&
Objects.equals(name, book.name) &&
Objects.equals(info, book.info);
}
@Override
public int hashCode() {
return Objects.hash(id, name, info);
}
public book() {
}
public static void main(String[] args) {
//创建Gson对象
Gson gson = new Gson();
//创建对象
book b = new book("01","海洋","海洋奥秘");
String s = gson.toJson(b);
//打印
System.out.println(s);
}
}