Hi I am trying to use Json Simple to select the “cheese” entry, however I seem to be returning “null” when I try to select it. Would be excellent to have some advice on how to do this?`
Here is the Json sample:
String s="[\"coins\",{\"wallet\":{\"shoppinglist\":{\"cheese\":{\"ingrediants\":[\"milk\",{\"preservative1\":\"wax\"}]}}}}]";
and here is the code:
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
It currently outputs:
["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
You’re skipping one step in the nesting.
obj2has the property “wallet”. “shoppinglist” is one level deeper.To get the intended result, use this: