NSDictionary to json string to json object using SwiftyJSON

前端 未结 2 2009
[愿得一人]
[愿得一人] 2021-02-09 07:33

I have a use case where I have an array of dictionaries and I need them as a json object:

var data = [Dictionary]()
//append items 
var byt         


        
2条回答
  •  天命终不由人
    2021-02-09 08:06

    I'm not sure what method you have on the 4th line there (JSON) but I got your code to work using NSJSONSerialization.JSONObjectWithData seen below:

    var data = [Dictionary]()
    data.append(["price":"1.20","city":"Foo","_id":"326105","street":"One"])
    data.append(["price":"1.20","city":"Bar","_id":"326104","street":"Two"])
    
    let bytes = try! NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.PrettyPrinted)
    var jsonObj = try! NSJSONSerialization.JSONObjectWithData(bytes, options: .MutableLeaves) as! [Dictionary]
    
    print(jsonObj)
    print(jsonObj[0])
    

    ... with output ...

    "[[price: 1.20, city: Foo, _id: 326105, street: One], [price: 1.20, city: Bar, _id: 326104, street: Two]]"
    
    "[price: 1.20, city: Foo, _id: 326105, street: One]"
    

    Edit: I see now the tag for swifty-json. I'm not familiar with that, but the code I included above works with the built in methods.

提交回复
热议问题