[英]accessing keys/values in JSONObject in java
In java I have the following code:在java中我有以下代码:
import org.json.JSONObject;
JSONObject obj = new JSONObject();
obj.put("firstKey", new JSONObject());
Now in the new object corresponding to the key "firstKey", I want to start inserting new key-value pairs, but I'm not sure how to do this.现在在与键“firstKey”对应的新对象中,我想开始插入新的键值对,但我不确定如何执行此操作。 I've tried oppJSON.get("firstKey").put("one","two");
我试过oppJSON.get("firstKey").put("one","two");
but this doesn't work - does anyone have any ideas?但这不起作用 - 有没有人有任何想法?
JSONObject 具有特定的获取方法,如getString
、 getInt
、 getDouble
等。在您的情况下,您需要getJSONObject
oppJSON.getJSONObject("firstKey").put("one","two");
Class JSONObject
implements a Map
without generics.类JSONObject
实现了一个没有泛型的Map
。 So while you can use Map<String, String>
, JSONObject
is the equivalent of Map<Object, Object>
.因此,虽然您可以使用Map<String, String>
,但JSONObject
等效于Map<Object, Object>
。 Everything pulled out of it using get
has to be cast to its type.使用get
从它中取出的所有东西都必须转换为它的类型。
Try ((JSONObject)obj.get("firstKey")).put("one", "two")
试试((JSONObject)obj.get("firstKey")).put("one", "two")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.