在 JSON 的实际应用场景中,除了生成符合规范的 JSON 数据,读取并解析已存在的 JSON 数据(如本地文件中的 JSON)是另一项核心技能。无论是处理配置文件中的 JSON 数据,还是读取外部存储的 JSON 格式业务数据,掌握从文件读取 JSON 并解析其中不同数据类型的方法,是将 JSON 理论落地到实际开发的关键环节。从文件读取 JSON 的流程通常包含依赖引入、数据文件准备、代码解析三个核心步骤,其中解析环节需要精准识别 JSON 中的 string、number、boolean、Array、null 等不同数据类型,并通过对应的 API 提取数据,这也能进一步巩固我们对 JSON 数据类型与数据结构的理解。接下来我们将通过完整的代码演示,详解从文件读取 JSON 数据的全流程,以及如何解析其中的各类数据类型。
代码演示:
// https://mvnrepository.com/artifact/commons-io/commons-io
compile group: 'commons-io', name: 'commons-io', version: '2.5'
{
"name" : "王小二",
"age" : 25.2,
"birthday" : "1990-01-01",
"school" : "蓝翔",
"major" : ["理发","挖掘机"],
"has_girlfriend" : false,
"car" : null,
"house" : null,
"comment" : "这是一个注释"
}
package com.myimooc.json.demo;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
/**
* 读取 JSON 数据演示类
* Created by ChangComputer on 2017/5/21.
*/
public class ReadJsonSample {
public static void main(String[] args) throws IOException {
createJsonByFile();
}
/**
* 读取 JSON 数据
* */
public static void createJsonByFile() throws IOException {
File file = new File(ReadJsonSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file,"UTF-8");
JSONObject jsonObject = new JSONObject(content);
System.out.println("姓名:"+jsonObject.getString("name"));
System.out.println("年龄:"+jsonObject.getDouble("age"));
System.out.println("有没有女朋友?:"+jsonObject.getBoolean("has_girlfriend"));
JSONArray majorArray = jsonObject.getJSONArray("major");
for (int i = 0 ; i < majorArray.length(); i++) {
System.out.println("专业"+(i+1)+":"+majorArray.get(i));
}
// 判断属性的值是否为空
if(!jsonObject.isNull("nickname")){
System.out.println("昵称:"+jsonObject.getDouble("nickname"));
}
}
}
isNull方法判断字段是否为 null,这也是处理 JSON null 值的重要技巧 —— 避免因读取不存在或值为 null 的字段导致程序异常。相比手动解析 JSON 字符串,使用 JSONObject 提供的 API 能高效、安全地处理各类数据类型,也体现了理解 JSON 数据类型规则对实际开发的重要性。掌握这套读取解析流程,不仅能应对本地 JSON 文件的处理场景,还能迁移到网络请求返回 JSON 数据的解析中(如接口返回的 JSON 字符串)。正在加载... ...