2

私はそのように機能する単純な Json パーサーを作成しています: Anyobject をデータとして含む JsonData クラスがあります。jsonData["key"] を使用すると、JsonData が返され、jsonData["key"]["key2"] などをチェーンできます。

私の質問は、そのクラスをどのように実装して、それをキャストして文字列と言うことができるかということです:

jsonData["key"] のようないくつかの回避策を使用せずに文字列として

jsonData["key"].data as String

コード:

   class JsonData:CustomStringConvertible{
    let data:AnyObject

        var description: String{
        get{
            return "\(data)"
        }
    }
    init(_ data: Data) {
        self.data = try! JSONSerialization.jsonObject(with: data, options: []) as! [[String:AnyObject]]
    }

    init(_ data: AnyObject)    {
        self.data = data
    }

    subscript(key:String) -> JsonData{
        let newData = data as! [String:AnyObject]
        let test = newData[key]!
        return JsonData(test)
    }
    subscript(index:Int) ->JsonData{
        let newData = data[index]!
        return JsonData(newData)
    }

}
4

1 に答える 1

0

In order to do this, you'd add another overload, but it won't work like you're thinking.

subscript(key: String) -> String {
    let newData = data as! [String:AnyObject]
    return newData[key] as! String
}

So then jsonData["key"] as String works, but jsonData["key"]["key2"] is ambiguous and you'd have to write it (jsonData["key"] as JsonData)["key2"] which probably isn't what you want.

The short answer to this is don't do this. If you need this much access to JSON, you're probably storing your data incorrectly. Parse it to structs as quickly as you can, and then work with structs. Convert the structs back to JSON when you want that. Extensive work with AnyObject is going to break your brain and the compiler over and over again. AnyObject is a necessary evil, not an every day tool. Soon you will encounter that terrible day that you have an AnyObject? and the compiler just breaks down in tears. Well, at least it isn't Any.

Putting that aside, the better solution is to use labeled-subscripts.

subscript(string key: String) -> String {
    let newData = data as! [String:AnyObject]
    return newData[key] as! String
}

Now you can access that as json[string: "key"] rather than json["key"] as String.

于 2016-07-18T16:25:43.480 に答える