我的json檔案的例子是
{
"collection": [
{
"trophy-name": {
"text": "swimming",
"text2": "fast swimming"
},
"length": "50m",
"pool": "outside",
"weather": "20"
}
]
}
現在我可以從長度、游泳池和天氣中獲取值。但我被困在如何訪問嵌套陣列嵌套物件上trophy-name。
我的代碼是:
public class main {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); // json path
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("collection");
for (Object number : array )
{
JSONObject testObj = (JSONObject) number;
String pool = (String)testObj.get("pool");
System.out.println(testObj.get("length"));
System.out.println(pool);
System.out.println(testObj.get("weather"));
}
}
}
這是我第一次嘗試使用 json 檔案,所以我正在嘗試使用它,因此代碼不是很好。
我可能必須創建新物件,例如
JSONObject trophyObj = (JSONObject) jsonObject.get("trophy-name");
然后從那里我應該能夠得到這個文本?
String troph = (String) trophyObj.get("text");
即使我是正確的,我也不知道如何將它實作到回圈中,或者是否有更好的方法來執行回圈?不要介意以不同的方式重做代碼,任何建議表示贊賞。
uj5u.com熱心網友回復:
是的,您是對的,只需提取JSONObject回圈內的 ,然后獲取所需的欄位。
public class main {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); // json path
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("collection");
for (Object number : array )
{
JSONObject testObj = (JSONObject) number;
String pool = (String)testObj.get("pool");
System.out.println(testObj.get("length"));
System.out.println(pool);
System.out.println(testObj.get("weather"));
JSONObject trophyObj = (JSONObject) testObj.get("trophy-name");
System.out.println((String)trophyObj.get("text"));
System.out.println((String)trophyObj.get("text2"));
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314435.html
上一篇:遞回到字典深度
下一篇:pd.read_csv用于“一列”匯入:其中sep避免拆分為:“ParserError:錯誤標記資料。C錯誤:第4行預期有10個欄位,看到16”
