如何访问JSONObject子字段?

我感到愚蠢,但我一直在寻找这个。 我正在使用谷歌地理编码器API,我需要一些json响应的帮助。 这是我拥有的JSONObject:

{ "viewport": { "southwest": { "lng": -78.9233749802915, "lat": 36.00696951970851 }, "northeast": { "lng": -78.92067701970849, "lat": 36.0096674802915 } }, "location_type": "ROOFTOP", "location": { "lng": -78.922026, "lat": 36.0083185 } } 

如何将“位置”子字段拉入自己的变量? 我试过jsonObjectVariable.getString("location");jsonObjectVariable.getDouble()等但它没有正确返回。 你在json对象中称为子字段是什么? 我已经读过你可以使用object.subobject语法访问子字段,但我只是没有得到我需要的东西。

(我使用json-org作为库)

谢谢您的帮助!

使用json.org Java库 ,您只能通过首先获取父JSONObject实例来获取对象的各个属性:

 JSONObject object = new JSONObject(json); JSONObject location = object.getJSONObject("location"); double lng = location.getDouble("lng"); double lat = location.getDouble("lat"); 

如果您尝试使用“点分表示法”访问属性,请执行以下操作:

 JSONObject object = new JSONObject(json); double lng = object.getDouble("location.lng"); double lat = object.getDouble("location.lat"); 

然后json.org库不是你想要的:它不支持这种访问。


作为一个副节点,在你的问题中给出的JSON的任何部分调用getString("location")是没有意义的。 被称为“location”的唯一属性的值是另一个具有两个属性“lng”和“lat”的对象。

如果你想要这个“作为一个字符串”,最接近的是调用JSONObject location上的toString() (这个答案中的第一个代码片段),这将给你类似{"lng":-78.922026,"lat":36.0083185}东西{"lng":-78.922026,"lat":36.0083185}

我相信你需要使用jsonObjectVariable.getJSONObject(“location”),后者又返回另一个JSONObject。

然后,您可以在该对象上调用getDouble(“lng”)或getDouble(“lat”)。

例如

 double lat = jsonObjectVariable.getJSONObject("location").getDouble("lat"); 

您应该创建类位置以拉出“位置”子字段。

 public class Location { private double lat; private double lng; @JsonCreator public Location(@JsonProperty("lat") double lat, @JsonProperty("lng") double lng { this.lat = lat; this.lngenter code here = lng; } 

您可以扩展JSONObject类并覆盖public Object get(String key) throws JSONException其中包含以下内容:

 public Object get(String key) throws JSONException { if (key == null) { throw new JSONException("Null key."); } Object object = this.opt(key); if (object == null) { if(key.contains(".")){ object = this.getWithDotNotation(key); } else throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return object; } private Object getWithDotNotation(String key) throws JSONException { if(key.contains(".")){ int indexOfDot = key.indexOf("."); String subKey = key.substring(0, indexOfDot); JSONObject jsonObject = (JSONObject)this.get(subKey); if(jsonObject == null){ throw new JSONException(subKey + " is null"); } try{ return jsonObject.getWithDotNotation(key.substring(indexOfDot + 1)); }catch(JSONException e){ throw new JSONException(subKey + "." + e.getMessage()); } } else return this.get(key); } 

请随意更好地处理exception..我确定它没有正确处理。 谢谢

Interesting Posts