标签:name tree 简介 his cat trace tst for cep
public class Book {
private String category;
private String tittle;
private String author;
private String year;
private String price;
public Book() {
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getTittle() {
return tittle;
}
public void setTittle(String tittle) {
this.tittle = tittle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
import java.util.List;
public class Person {
private String name;
private int age;
private List<Integer> scores;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Integer> getScores() {
return scores;
}
public void setScores(List<Integer> scores) {
this.scores = scores;
}
}
[
{"category":"科幻","tittle":"三体","author":"lisi","year":"2018/01/05","price":"28"},
{"category":"科幻","tittle":"四体","author":"lisi","year":"2018/01/05","price":"28"}
]
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
public class JsonTest {
public static void main(String[] args) {
testJsonObject();
testJsonFile();
}
public static void testJsonObject(){
//构造对象
Person p = new Person();
p.setName("zhangsan");
p.setAge(18);
p.setScores(Arrays.asList(60,70,80));
//从java对象到json字符串
Gson gson = new Gson();
String str = gson.toJson(p);
System.out.println(str);
//从json字符串到Java对象
Person p1 = gson.fromJson(str,Person.class);
System.out.println(p1.getName());//zhangsan
System.out.println(p1.getAge());//18
System.out.println(p1.getScores());//[60,70,80]
//调用GSON的JsonObject
JsonObject json = gson.toJsonTree(p).getAsJsonObject();//将json解析为一棵树
System.out.println(json.get("name"));//"zhangsan"
System.out.println(json.get("age"));//18
System.out.println(json.get("scores"));//[60,70,80]
}
public static void testJsonFile(){
//从json文件进行加载并重构为java对象
Gson gson = new Gson();
File file = new File("book.json");
try(FileReader reader = new FileReader(file)){
List<Book> books = gson.fromJson(reader,new TypeToken<List<Book>>(){}.getType());
for(Book book:books){
System.out.println(book.getAuthor()+" "+book.getTittle());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
标签:name tree 简介 his cat trace tst for cep
原文地址:https://www.cnblogs.com/cstdio1/p/12234374.html