利用JSONObject解析xxx.json格式文件
准备两个工具依赖
操作文件的io依赖jar包
JSONObject相关jar包
<dependencies>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<!--json解析依赖-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<!--引入io包,对文件进行解析-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
测试结构
pom.xml文件
test.json文件内容
{
"hobbies": [
"hiking",
"swimming"
],
"sex": "male",
"name": "John",
"is_student": true,
"age": 22
}
代码测试片段
public class Exam01 {
public static void main(String[] args) throws IOException {
//准备file文件
File file = new File("D:\\idea_work\\practise\\src\\main\\java\\test.json");
//通过fileutils拿到文件的字符串
String str = FileUtils.readFileToString(file);
System.out.println(str);
//对基本类型的解析
JSONObject obj = new JSONObject(str);
Object name = obj.get("name");
System.out.println("name:"+name);
System.out.println("---------------");
Object hobbies = obj.get("hobbies");
System.out.println("hobbies:"+hobbies);
}
}
测试结果,先代码后分析
{
"hobbies": [
"hiking",
"swimming"
],
"sex": "male",
"name": "John",
"is_student": true,
"age": 22
}
name:John
---------------
hobbies:["hiking","swimming"]
完整解析代码
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
public class Exam01 {
public static void main(String[] args) throws IOException {
//准备file文件
File file = new File("D:\\idea_work\\practise\\src\\main\\java\\test.json");
//通过fileutils拿到文件的字符串
String str = FileUtils.readFileToString(file);
//对基本类型的解析
JSONObject obj = new JSONObject(str);
//获取名字然后打印
Object name = obj.get("name");
System.out.println("name:"+name);
//获取性别,然后打印
Object sex = obj.get("sex");
System.out.println("sex:"+sex);
//获取是否是学生,然后打印
Object is_student = obj.get("is_student");
System.out.println("is_student:"+is_student);
//获取年龄,然后打印
Object age = obj.get("age");
System.out.println("age:"+age);
//获取数组,然后打印
Object hobbies = obj.get("hobbies");
System.out.println("hobbies数组:"+hobbies);
//对数组进行解析,拿到里面的值
JSONArray hobbiesArray = obj.getJSONArray("hobbies");
//通过for循环遍历数组的内容
for(int i=0;i<hobbiesArray.length();i++){
String s = (String)hobbiesArray.get(i);
System.out.println("hobbiesArray["+i+"]:"+s);
}
}
}
结果
name:John
sex:male
is_student:true
age:22
hobbies数组:["hiking","swimming"]
hobbiesArray[0]:hiking
hobbiesArray[1]:swimming
Process finished with exit code 0
解析xxx.json格式文件思路回顾
1.导入需要的工具类jar包JSONObject common-io
2.构建file文件,然后解析该文件
3.拿到json解析对象,调用get(“key”),obj.getJSONArray(“hobbies”)方法拿到对应的值,值的结果根据json文件可能为string字符串,或者数组
4.拿到字符串做其他操作
5.拿到数组进行操作,比如解析该数组,拿到索引对应的值
ok,tata!