如何访问JSONObject子字段?

时间:2012-04-17 19:42:14

标签: java json google-geocoder

我感到愚蠢,但我一直在寻找这个。我正在使用谷歌地理编码器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作为库)

感谢您的帮助!

4 个答案:

答案 0 :(得分:17)

使用json.org library for 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”的对象。

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

答案 1 :(得分:4)

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

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

E.g。

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

答案 2 :(得分:0)

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

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;
    }

答案 3 :(得分:-1)

您可以扩展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);
}

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

相关问题