在 JSON 的完整应用链路中,解析是与生成同等重要的核心环节 —— 而 GSON 框架不仅能高效生成 JSON,其解析能力更是贴合 JSON 数据类型与数据结构的特性,能将 JSON 字符串精准映射为 Java 对象,大幅降低手动解析的复杂度。相比原生 JSONObject 逐字段提取数据的方式,GSON 支持直接将 JSON 数据反序列化为 Java Bean,自动适配 JSON 的 string、number、boolean、Array、null 等核心数据类型,还能处理日期、集合等复杂类型的解析,是企业级开发中解析 JSON 的最优选择。接下来我们将通过完整的代码演示,详解 GSON 解析 JSON 文件的全流程,深入理解 GSON 如何适配 JSON 数据类型与结构的解析规则。
代码演示:
package com.myimooc.json.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.myimooc.json.demo.ReadJsonSample;
import com.myimooc.json.model.Diaosi;
import com.myimooc.json.model.DiaosiWithBirthday;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
/**
* 使用Gson解析 JSON 文件
* Created by ChangComputer on 2017/5/21.
*/
public class GsonReadSample {
public static void main(String[] args) throws IOException {
createJsonByGsonFile();
}
/**
* 读取 JSON 数据
* */
public static void createJsonByGsonFile() throws IOException {
File file = new File(GsonReadSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file,"UTF-8");
// 无日期转换
Gson gson = new Gson();
Diaosi wangxiaoer = gson.fromJson(content,Diaosi.class);
System.out.println(wangxiaoer.toString());
// 带日期转换
Gson gson2 = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
DiaosiWithBirthday wangxiaoer2 = gson2.fromJson(content,DiaosiWithBirthday.class);
System.out.println(wangxiaoer2.getBirthday().toString());
// 集合类解析
System.out.println(wangxiaoer2.getMajor());
System.out.println(wangxiaoer2.getMajor().getClass());
}
}
fromJson方法能自动将 JSON 字符串中的name(string)映射为 Java Bean 的 String 类型、age(number)映射为 double 类型、has_girlfriend(boolean)映射为 boolean 类型、major(Array)映射为数组 / 集合类型、car/house(null)映射为 Java 的 null 值,完全遵循 JSON 核心数据类型与 Java 类型的对应规则,无需手动逐字段解析;从进阶解析来看,通过GsonBuilder配置日期格式,能将 JSON 中的字符串类型日期(如 "1990-01-01")精准转化为 Java 的 Date 类型,解决了 JSON 无原生日期类型的解析痛点;而集合类解析则体现了 GSON 对 JSON Array 结构的灵活适配,能自动将 JSON 数组转化为对应的 Java 集合类型。相比原生 JSONObject 解析的繁琐,GSON 的优势在于 “一键映射”—— 将 JSON 数据结构直接转化为面向对象的 Java Bean,既降低了代码量,又通过强类型约束减少了解析错误。掌握 GSON 解析的方法,不仅能巩固 JSON 数据类型与结构的理论知识,更能应对实际项目中复杂的 JSON 解析场景(如嵌套结构、特殊类型解析)。正在加载... ...