2012-02-04 39 views
0

嗨我試圖用Json Simple來選擇「cheese」條目,但是當我嘗試選擇它時,我似乎返回「null」。將優秀的有關於如何做到這一點一些建議`JsonSimple:如何獲得Json Feed中的第二個對象

這裏是JSON的示例:

String s="[\"coins\",{\"wallet\":{\"shoppinglist\":{\"cheese\":{\"ingrediants\":[\"milk\",{\"preservative1\":\"wax\"}]}}}}]"; 

這裏是代碼:

 System.out.println(s); 
     System.out.println("=======decode======="); 

     Object obj=JSONValue.parse(s); 
     JSONArray array=(JSONArray)obj; 
     System.out.println("======the 2nd element of array======"); 
     System.out.println(array.get(1)); 
     System.out.println(); 
     System.out.println("======the 1st element of array======"); 
     System.out.println(array.get(0)); 
     System.out.println(); 



     JSONObject obj2=(JSONObject)array.get(1); 
     System.out.println("======field \"1\"=========="); 
     System.out.println(obj2.get("wallet")); 


     JSONObject obj3=(JSONObject) obj2.get("shoppinglist"); 
     System.out.println("======field \"2\"=========="); 
     System.out.println(obj3); //This figure is returning null when I would like it to return the json object shopping list 

目前,它輸出:

 
    ["coins",{"wallet":{"shoppinglist":{"cheese":{"ingrediants":["milk",{"preservative1":"wax"}]}}}}] 
    =======decode======= 
    ======the 2nd element of array====== 
    {"wallet":{"shoppinglist":{"cheese":{"ingrediants":["milk",{"preservative1":"wax"}]}}}} 

    ======the 1st element of array====== 
    coins 

    ======field "1"========== 
    {"shoppinglist":{"cheese":{"ingrediants":["milk",{"preservative1":"wax"}]}}} 
    ======field "2"========== 
    null 

回答

1

您正在跳過嵌套中的一步。 obj2有財產「錢包」。 「購物清單」更深一層。

要獲得預期的結果,使用此:

JSONObject wallet  = (JSONObject) obj2.get("wallet"); 
JSONObject shoppinglist = (JSONObject) wallet.get("shoppinglist"); 
System.out.println(shoppinglist); 
+0

這會教我一個教訓爲:努力成爲一個智者,在我system.outs做工作,不具有良好的名字命名我的變量。學過的知識! - 謝謝! – 2012-02-04 18:32:03