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