JSON或JavaScript Object Notation是一种轻量级的基于文本的开放标准,旨在用于人类可读的数据交换。JSON使用的约定是程序员已知的,包括C,C ++,Java,Python,Perl等。JSON文档样本-{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
Json-简单库
json-simple是一个轻量级的库,用于处理JSON对象。使用此程序,您可以使用Java程序读取或写入JSON文档的内容。
JSON-简单的Maven依赖
以下是JSON简单库的maven依赖关系-
com.googlecode.json-simple
json-simple
1.1.1
301 to 305
将其粘贴在pom.xml文件末尾的 dependencies>标记中。(在 project>标记之前)
示例
首先,让我们创建一个名称为sample.json的JSON文档,其中包含6个键值对,如下所示-{
"ID": "1",
"First_Name": "Shikhar",
"Last_Name": "Dhawan",
"Date_Of_Birth": "1981-12-05",
"Place_Of_Birth":"Delhi",
"Country": "India"
}
使用Java程序读取JSON文件的内容-实例化json-简单库的JSONParser类。JSONParser jsonParser = new JSONParser();使用parse()方法解析获得的对象的内容。//解析JSON文件的内容
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json"));使用get()方法检索与键关联的值。String value = (String) jsonObject.get("key_name");
以下Java程序解析上面创建的sample.json文件,读取其内容并显示它们。
示例import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadingJSON {
public static void main(String args[]) {
//创建一个JSONParser对象
JSONParser jsonParser = new JSONParser();
try {
//解析JSON文件的内容
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/sample.json"));
String id = (String) jsonObject.get("ID");
String first_name = (String) jsonObject.get("First_Name");
String last_name = (String) jsonObject.get("Last_Name");
String date_of_birth = (String) jsonObject.get("Date_Of_Birth");
String place_of_birth = (String) jsonObject.get("Place_Of_Birth");
String country = (String) jsonObject.get("Country");
//形成网址
System.out.println("Contents of the JSON are: ");
System.out.println("ID :"+id);
System.out.println("First name: "+first_name);
System.out.println("Last name: "+last_name);
System.out.println("Date of birth: "+date_of_birth);
System.out.println("Place of birth: "+place_of_birth);
System.out.println("Country: "+country);
System.out.println(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出结果Contents of the JSON are:
ID :1
First name: Shikhar
Last name: Dhawan
Date of birth :1981-12-05
Place of birth: Delhi
Country: India