如何使用SwiftyJSON中元素的路径获取字符串

时间:2016-06-08 14:26:44

标签: ios swift alamofire swifty-json

int id=0;
do {
    URL url = new URL("https://api.github.com/repositories?since="+id+"&access_token="+oauth);
    // implement callApi such as Json.createReader(url.openStream()), but please make it sleep for a minute if the limit got reached        
    try (JsonReader rdr = callApi(url)) {
        JsonArray results = rdr.readArray();
        for (JsonObject result : results.getValuesAs(JsonObject.class)) {
            id = result.getInt("id");
            String name = result.getString("name");
            boolean priv = result.getBoolean("private");
            ... do whatever you want...
        }
    }
} while (some stop condition);

在SwiftyJSON状态的文档中,我们可以使用路径来获取元素。

//With an array like path to the element
let path = [1,"list",2,"name"]
let name = json[path].string 
//Just the same
let name = json[1]["list"][2]["name"].string

我尝试使用路径来简化代码,但我无法定义有效路径。

    let displayLocationFull = swiftyJson["current_observation"]["display_location"]["full"].stringValue
    let displayLocationCity = swiftyJson["current_observation"]["display_location"]["city"].stringValue
    let displayLocationState = swiftyJson["current_observation"]["display_location"]["state"].stringValue
    let displayLocationStateName = swiftyJson["current_observation"]["display_location"]["state_name"].stringValue
    let displayLocationCountry = swiftyJson["current_observation"]["display_location"]["country"].stringValue
    let displayLocationCountry_iso3166 = swiftyJson["current_observation"]["display_location"]["country_iso3166"].stringValue
    let displayLocationZip = swiftyJson["current_observation"]["display_location"]["zip"].stringValue
    let displayLocationMagic = swiftyJson["current_observation"]["display_location"]["magic"].stringValue
    let displayLocationWMO = swiftyJson["current_observation"]["display_location"]["wmo"].stringValue
    let displayLocationLatitude = swiftyJson["current_observation"]["display_location"]["latitude"].stringValue
    let displayLocationLongitute = swiftyJson["current_observation"]["display_location"]["longitude"].stringValue
    let displayLocationElevation = swiftyJson["current_observation"]["display_location"]["elevation"].stringValue

这是路径,显示错误。

任何人都可以告诉我该怎么办? 谢谢

0 个答案:

没有答案