【问题标题】:SwiftyJSON parse json querySwiftyJSON 解析 json 查询
【发布时间】:2016-12-09 01:50:09
【问题描述】:

我正在 swift 3 中编写代码,用于解析来自 http 请求的 json 格式结果的查询。

json格式为:

JSON: {
base = stations;
coord =     {
    lat = "23.9";
    lon = "42.89";
};
weather =     (
            {
        description = mist;
        icon = 50n;
        id = 701;
        main = Mist;
    },
            {
        description = fog;
        icon = 50n;
        id = 741;
        main = Fog;
    }
);
wind =     {
    deg = "222.506";
    speed = "1.72";
};}

我的代码是:

Alamofire.request(url).responseJSON { response in

        if let a = response.result.value  {

            let jsonVar = JSON(a)

            if let resDati = jsonVar["base"].string {
                print(resDati as String)  // <- OK
            }

            if let dati2 = jsonVar["weather"].array {

                for item in dati2 {

                    print(" > \(item["main"])") // <- OK

                }

            }

        } else {
            print(Error.self)
        }

    }

问题在于我尝试过的“坐标”和“风”数据:

if let dati4 = jsonVar["wind"].array {

    for item in dati4 {

        print("-- \(item)")

    } }

我无法以 json 格式打印与“wind”和“coord”相关的数据。

我该如何解决这个问题。

谢谢。

【问题讨论】:

    标签: ios json swift3 xcode8 swifty-json


    【解决方案1】:

    wind 包含字典,而不是数组,您可以使用 SwiftyJSON 和以下代码获取 degspeed 值:

    if let wind = jsonVar["wind"].dictionary,
        let deg = wind["deg"]?.double,
        let speed = wind["speed"]?.double {
        print(deg, speed)
    }
    

    coord 相应地工作

    if let coord = jsonVar["coord"].dictionary,
        let lat = coord["lat"]?.double,
        let lon = coord["lon"]?.double {
        print(lat, lon)
    }
    

    注意:所有值都是Double 类型,json 格式 具有误导性。

    【讨论】:

    • 我写了你的代码,但是'deg'和'speed'的结果是nil。
    • 如果jsonVar["base"] 打印了一些东西(&lt;- OK),我的代码应该可以工作。也是。
    • 我已在我的代码中添加了您的代码,并在控制台中打印了“base”和“weather”,但没有打印“wind”,所以我将“let deg”和“let speed”从“如果',在控制台中我看到'nil nil'。
    • 那么你发布的JSON(实际上不是JSON)是错误的。根据转储weatherwind 处于同一级别,并且两个值都是字符串。
    • 感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多