Json Simple:如何在Json feed中获取第二个对象

时间:2012-02-04 13:25:59

标签: java json

您好我正在尝试使用Json Simple来选择“cheese”条目,但是当我尝试选择它时,我似乎正在返回“null”。对于如何做到这一点有一些建议会很好吗?`

这是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 个答案:

答案 0 :(得分:1)

您正在跳过嵌套中的一个步骤。 obj2拥有“钱包”属性。 “购物清单”更深一层。

要获得预期结果,请使用:

JSONObject wallet       = (JSONObject) obj2.get("wallet");
JSONObject shoppinglist = (JSONObject) wallet.get("shoppinglist");
System.out.println(shoppinglist);
相关问题