1.pom.xml配置
com.googlecode.json-simple
json-simple
1.1
2.准备JSON数据文件jsonTestFile.json
{
"id": 1,
"firstname": "Katerina",
"languages": [
{
"lang": "en",
"knowledge": "proficient"
},
{
"lang": "fr",
"knowledge": "advanced"
}
],
"job": {
"site": "www.javacodegeeks.com",
"name": "Java Code Geeks"
}
}
3.Java 解析类
package com.javacodegeeks.javabasics.jsonparsertest;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParseTest {
private static final String filePath = "C:\\Users\\katerina\\Desktop\\jsonTestFile.json";
public static void main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
// get a String from the JSON object
String firstName = (String) jsonObject.get("firstname");
System.out.println("The first name is: " + firstName);
// get a number from the JSON object
long id = (long) jsonObject.get("id");
System.out.println("The id is: " + id);
// get an array from the JSON object
JSONArray lang= (JSONArray) jsonObject.get("languages");
// take the elements of the json array
for(int i=0; i
System.out.println("The " + i + " element of the array: "+lang.get(i));
}
Iterator i = lang.iterator();
// take each value from the json array separately
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
System.out.println("language "+ innerObj.get("lang") +
" with level " + innerObj.get("knowledge"));
}
// handle a structure into the json object
JSONObject structure = (JSONObject) jsonObject.get("job");
System.out.println("Into job structure, name: " + structure.get("name"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
这篇博客演示了如何在Java中使用json-simple库来解析JSON数据。首先,介绍了pom.xml配置中引入json-simple的依赖。接着,提供了一个JSON数据文件作为示例。在Java解析类中,通过FileReader读取JSON文件,使用JSONParser解析数据。然后从JSONObject获取字符串、长整型数据,遍历并打印JSONArray中的元素,以及解析嵌套的JSONObject。整个过程展示了Java处理JSON的基本步骤。
1万+

被折叠的 条评论
为什么被折叠?



