如何在 Java 中解析嵌套的 JSON 对象

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

在本 Java 教程中,我们将使用库 JSON.simple 解析或读取嵌套的 JSON 对象。 要解析Nested Object,我们需要先创建父对象的对象。
nestedobjects.json

{
  "name": "Mukul Sharma",
  "website": "www.websparrow.org",
  "technology": {
    "java": 8
  },
  "compose": {
    "total": 1,   
    "soundex": [
      {  
        "info": {
          "date_of_birth": "22-10-2016",
          "name_id": "ttr876"                   
        }
      }
    ]
  }
}

上面的 JSON 文件简单地解释了一个对象里面有一个对象。

检查完整示例

JsonNestedParseExample.java

package org.websparrow;

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 JsonNestedParseExample {

	public static void main(String[] args) {

		JSONParser jsonParser = new JSONParser();
		Object object;

		try {

			object = jsonParser.parse(new FileReader("nestedobjects.json"));
			JSONObject jsonObject = (JSONObject) object;

			String name = (String) jsonObject.get("name");
			System.out.println("Name: " + name);

			String website = (String) jsonObject.get("website");
			System.out.println("Website: " + website);

			JSONObject technology = (JSONObject) jsonObject.get("technology");
			System.out.println("Technology: " + technology);
			long java = (Long) technology.get("java");
			System.out.println("\tjava: " + java);

			JSONObject compose = (JSONObject) jsonObject.get("compose");
			System.out.println("compose: " + compose);
			long total = (Long) compose.get("total");
			System.out.println("\ttotal: " + total);
			JSONArray soundex = (JSONArray) compose.get("soundex");
			System.out.println("\tsoundex: " + soundex);

			Object composeObj = jsonObject.get("compose");
			JSONObject jsonObject1 = (JSONObject) composeObj;
			Iterator itr = soundex.iterator();

			while (itr.hasNext()) {

				Object slide = itr.next();
				JSONObject jsonObject2 = (JSONObject) slide;
				JSONObject info = (JSONObject) jsonObject2.get("info");

				String date_of_birth = (String) info.get("date_of_birth");
				String name_id = (String) info.get("name_id");

				System.out.println("\t\tDate of Birth: " + date_of_birth);
				System.out.println("\t\tName Id: " + name_id);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

输出:

Name: Mukul Sharma
Website: www.websparrow.org
Technology: {"java":8}
	java: 8
compose: {"total":1,"soundex":[{"info":{"date_of_birth":"22-10-2016","name_id":"ttr876"}}]}
	total: 1
	soundex: [{"info":{"date_of_birth":"22-10-2016","name_id":"ttr876"}}]
		Date of Birth: 22-10-2016
		Name Id: ttr876

相关文章

微信公众号

最新文章

更多