欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Gson的使用--基础

程序员文章站 2024-03-16 08:52:16
...

翻译一篇来自javacreed的关于Gson的文章

基本用法

Gson gson = new GsonBuilder().create()
#或者 Gson gson = new Gson();
#Java Object转换为Json
gson.toJson("hello",System.out);
gson.toJson(123,System.out);

会输出
"hello"123

Java Object序列化到文件

FileWriter writer = new FileWriter("out.json");
Gson gson = new GsonBuilder().create();
gson.toJson("hell0",writer);
gson.toJson(123,writer);
writer.close();

从文件中读取Json并转换成Java Object

try(Reader reader = new 
InputStreamReader(this.class.getResourceAsStream("out.json"))){
  Gson gson = new GsonBuilder().create();
  Person p = gson.fromJson(reader, Person.class);
}

讨论一下嵌套的Json对象

{
  "name":"chico",
  "age":18,
  "exam":{
    "subject":"English",
    "score":100
  }
}

依然是Person类(必须有一个默认的构造函数)

public class Person{
  private String name;
  private int age;
  private Exam exam;
}

然后是Exam类

public class Exam{
  private String subject;
  private int score;
}

反序列化部分依然不变

try(Reader reader = new 
InputStreamRead(this.class.getResourceAsStream("out.json"))){
  Gson gson = new GsonBuilder().create();
  Person p = gson.fromJson(reader,Person.class);
}

常用的Gson解析类型

1.解析成list

[{"age":10,"name":"chico"},{"age":10,"name":"dong"}]

Gson gson = new GsonBuilder().create();
List<Person> list = gson.fromJson(jsonString,
  new TypeToke<List<Person>>(){}.getType());

2.解析成Map

{"p1":{"age":10,"name":"chico"},"p2":{"age":10,"name":"dong"}}

Gson gson = new GsonBuilder().create();
Map<String,Person> map =
  gson.fromJson(jsonString,
    new TypeToken<Map<String,Person>>(){}.getType());

3.解析节点

{"flag":true, "data":{"score":100,"name":"chico"}}

JsonParser  parser = new JsonParser();
JsonElement element = parser.parse(jsonString);
JsonObject root = element.getAsJsonObject();

JsonPrimitive jsonFlag = root.getAsJsonPrimitive("flag");
boolean flag = jsonFlag.getAsBoolean();

JsonObject jsonData = root.getAsJsonObject("data");
Data data = new Gson().fromJson(jsonData, Data.class);