使用Swift在正确的json中使用错误的值

时间:2017-09-19 06:43:02

标签: ios json swift parsing swift3

我面对这个奇怪的问题。我必须解析这个json并提取"符号"," High"," low"和"方向"。这是原来的json

    [{"ID":101,"Symbol":"PKR","Bid":105.7,"Ask":106,"High":105.7,"Low":106,"Change":0,"Direction":"0","CreateDate":"04:38:26","EntityState":2,
"EntityKey":{"EntitySetName":"v_openmarketrates","EntityContainerName":"tradebizEntities",
"EntityKeyValues":[{"Key":"ID","Value":101}],
"IsTemporary":false}},

    {"ID":1,"Symbol":"EUR","Bid":126.696,"Ask":127.327,"High":126.7622,"Low":126.9752,"Change":0.4192,"Direction":"0","CreateDate":"06:37:31","EntityState":2,
"EntityKey":{"EntitySetName":"v_openmarketrates","EntityContainerName":"tradebizEntities","EntityKeyValues":[{"Key":"ID","Value":1}],
"IsTemporary":false}}]

当我在json中解析它时,除了" Direction"的值之外,它正确地获取所有值,如下所示:

    [{
    Ask = 106;
    Bid = "105.7";
    Change = 0;
    CreateDate = "04:38:26";
    Direction = 0;
    EntityKey =     {
        EntityContainerName = tradebizEntities;
        EntityKeyValues =         (
                        {
                Key = ID;
                Value = 101;
            }
        );
        EntitySetName = "v_openmarketrates";
        IsTemporary = 0;
    };
    EntityState = 2;
    High = "105.7";
    ID = 101;
    Low = 106;
    Symbol = PKR;
},

    {
            Ask = "127.265";
            Bid = "126.623";
            Change = "0.3463";
            CreateDate = "06:30:46";
            Direction = 0;
            EntityKey =     {
                EntityContainerName = tradebizEntities;
                EntityKeyValues =         (
                                {
                        Key = ID;
                        Value = 1;
                    }
                );
                EntitySetName = "v_openmarketrates";
                IsTemporary = 0;
            };
            EntityState = 2;
            High = "126.7306";
            ID = 1;
            Low = "126.9752";
            Symbol = EUR;
        }

我不知道在解析时json内部的值是如何变化的,即使其余的值是正确的。这就是我解析它的方式。

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: [])  as? [NSDictionary] {
                print("kerb rates full json = ",jsonResult )
                for field in jsonResult as? [AnyObject] ?? [] {
                    print("fields of kerb rates = \(field)")

                    print("kerb directions \((field["Direction"] as? String)!)")

                    let subfield : AnyObject = (field["EntityKey"] as? AnyObject)!
                    let sub_subfield : AnyObject = (subfield["EntityKeyValues"] as? AnyObject)!
                    print("sub_subfield = \(sub_subfield)")
                    print("subfields = \(subfield)")

                //    for key_Subfield in sub_subfield as? [AnyObject] ?? [] {

                        print("inside loop!")
                        // converting int and bool values
                        let ask = (field["Ask"] as? Int)!
                        let bid = (field["Bid"] as? Int)!
                        let change = (field["Change"] as? Int)!
                        let EntityState = (field["EntityState"] as? Int)!
                        let High = (field["High"] as? Double)!
                        let ID = (field["ID"] as? Int)!
                        let IsTemporary = ""//(subfield["IsTemporary"] as? Bool)!
                        let Low = (field["Low"] as? Double)!
                        let Value = ""//(key_Subfield["Value"] as? Int)!


                        // it is crashing here due to multple dictionaries
                        self.Save_KerbRates(ask: (String(ask)),
                                           bid: (String(bid)),
                                           change: (String(change)),
                                           createDate: (field["CreateDate"] as? String)!,
                                           direction: (field["Direction"] as? String)!,
                                           entityContainerName: "",//(subfield["EntityContainerName"] as? String)!,
                                           entitiySetName:"",// (subfield["EntitySetName"] as? String)!,
                                           entitiyState: (String(EntityState)),
                                           high: (String(High)),
                                           id: (String(ID)),
                                           isTemporary: (String(IsTemporary)),
                                           key:"",// (key_Subfield["Key"] as? String)!,
                                           low: (String(Low)),
                                           symbol: (field["Symbol"] as? String)!,
                                           value: (String(Value)))


                  //  }
                }

更新

使用[[String:Any]]

之后

我仍然得到错误的方向值,比如

    kerb rates full json =  [["Low": 106, "Direction": 0, "EntityState": 2, "EntityKey": {
    EntityContainerName = tradebizEntities;
    EntityKeyValues =     (
                {
            Key = ID;
            Value = 101;
        }
    );
    EntitySetName = "v_openmarketrates";
    IsTemporary = 0;
}, "ID": 101, "CreateDate": 04:38:26, "Symbol": PKR, "Change": 0, "Ask": 106, "High": 105.7, "Bid": 105.7], ["Low": 126.9752, "Direction": -1, "EntityState": 2, "EntityKey": {
    EntityContainerName = tradebizEntities;
    EntityKeyValues =     (
                {
            Key = ID;
            Value = 1;
        }
    );
    EntitySetName = "v_openmarketrates";
    IsTemporary = 0;
}, "ID": 1, "CreateDate": 07:03:46, "Symbol": EUR, "Change": 0.4403, "Ask": 127.349, "High": 126.7654, "Bid": 126.717],

1 个答案:

答案 0 :(得分:0)

这解析(并打印)字典第一级中的所有值以及第二级中键IsTemporaryValue的值。所有变量名都以小写字母开头,以符合命名约定。

为方便起见,代码使用了类型别名。

请注意,代码不会使用任何错误处理来检查字典键。如果无法保证所有项目都包含所有键和值,则必须使用可选绑定。

typealias JSONDictionary = [String:Any]

do {
    if let jsonResult = try JSONSerialization.jsonObject(with:data!) as? [JSONDictionary] {

        for field in jsonResult {

            let ask = field["Ask"] as! Double
            let bid = field["Bid"] as! Double
            let change = field["Change"] as! Double
            let createDate = field["CreateDate"] as! String
            let direction = field["Direction"] as! String
            let entityState = field["EntityState"] as! Int
            let high = field["High"] as! Double
            let id = field["ID"] as! Int
            let low = field["Low"] as! Double
            let symbol = field["Symbol"] as! String

            let entityKey = field["EntityKey"] as! JSONDictionary
            let isTemporary = entityKey["IsTemporary"] as! Bool

            let entityKeyValues = entityKey["EntityKeyValues"] as! [JSONDictionary]
            let value = entityKeyValues[0]["Value"] as! Int
            print(ask, bid, change, createDate, direction, entityState, high, id, low, symbol, isTemporary, value)
        }

    }
} catch {
    print(error)
}