如何在 Java 中解析 JSON

x33g5p2x  于2021-10-26 转载在 Java  
字(1.7k)|赞(0)|评价(0)|浏览(302)

在本 Java 教程中,我们将使用 java 程序解析 JSON 数据。 要解析 JSON 对象,我们需要添加一些额外的 jar/library。 在这个例子中,我使用 JSON.simple 来解析对象。 您可以通过其他 API 执行此操作,例如 GsonJackson 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

相关文章

微信公众号

最新文章

更多