[英]How can I get JSON values inside an iterator in Java
我有這個 JSON 文件我的 JSON 文件
我想在 Java 中在 System.Out 中顯示此代碼段的內容:
else if(jsonObject2.get("type").equals("link")){
System.out.println(jsonObject2.get("tr_name"));
System.out.println(jsonObject2.get("tr_description"));
System.out.println(jsonObject2.get("tr_rules"));
System.out.println(jsonObject2.get("source"));
System.out.println(jsonObject2.get("target"));
}
到目前為止,我可以成功獲得tr_name
,即LINKNAME
,但由於tr_description
、 tr_rules
、 source
和target
更深入,我無法訪問它們。 從source
和target
我需要得到他們的id
。
請問我怎樣才能得到它們?
我的完整 Java 代碼如下:
package jsontoxml;
import java.io.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;
public class JacksonStreamExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("text.json"));
JSONObject jsonObject = (JSONObject) obj;
//Check inside the JSON array with all graph objects
JSONArray cells = (JSONArray) jsonObject.get("cells");
//Check inside the JSON object with all graph objects
Iterator<JSONObject> iterator = cells.iterator();
while(iterator.hasNext()){
JSONObject jsonObject2 = (JSONObject) iterator.next();
if(jsonObject2.get("type").equals("link")){
System.out.println(jsonObject2.get("tr_name"));
System.out.println(jsonObject2.get("tr_description"));
System.out.println(jsonObject2.get("tr_rules"));
System.out.println(jsonObject2.get("source"));
System.out.println(jsonObject2.get("target"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
到目前為止,我的系統輸出是:
LINKNAME
null
null
{"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24"}
{"id":"d23133e0-e516-4f72-8127-292545d3d479"}
試試下面的代碼 -
System.out.println(jsonObject2.get("tr_name"));
System.out.println(((JSONObject) ((JSONObject) jsonObject2.get("attrs")).get(".attributes"))
.get("tr_description"));
System.out.println(
((JSONObject) ((JSONObject) jsonObject2.get("attrs")).get(".attributes")).get("tr_rules"));
System.out.println(((JSONObject) jsonObject2.get("source")).get("id"));
System.out.println(((JSONObject) jsonObject2.get("target")).get("id"));
輸出 -
LINKNAME2
LINKDESCRIPTION2
null
a53898a5-c018-45c4-bd3f-4ea4d69f58ed
e2bd21f2-508d-44b9-9f68-e374d4fa87ea
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.