在本 Java 教程中,我们将使用 java 程序解析 JSON
数据。 要解析 JSON 对象,我们需要添加一些额外的 jar/library。 在这个例子中,我使用 JSON.simple 来解析对象。 您可以通过其他 API 执行此操作,例如 Gson
或 Jackson 2
。
数据.json
{
"founded":2016,
"name":"websparrow.org",
"articles":["java","struts","web"],
"location":"India"
}
下载 JSON.simple jar 或在您的项目中添加 maven/gradle 依赖项。
pom.xml
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
build.gradle
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
JsonParseExample.java
package org.websparrow;
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonParseExample {
public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
try {
Object object = jsonParser.parse(new FileReader("data.json"));
JSONObject jsonObject = (JSONObject) object;
// System.out.println(jsonObject);
long founded = (Long) jsonObject.get("founded");
System.out.println("founded: " + founded);
String location = (String) jsonObject.get("location");
System.out.println("location: " + location);
String name = (String) jsonObject.get("name");
System.out.println("name: " + name);
JSONArray articles = (JSONArray) jsonObject.get("articles");
Iterator itr = articles.iterator();
System.out.print("articles:");
while (itr.hasNext()) {
System.out.print(" " + itr.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出:
founded: 2016
location: India
name: websparrow.org
articles: java struts web
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/how-to-parse-json-in-java
内容来源于网络,如有侵权,请联系作者删除!