最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift 将json字符串转换为json字典变量

Swift crifan 4962浏览 0评论

需要用swift将json字符串:

{
  "active": true,
  "contacts": [],
  "doc_type": "user",
  "email": "[email protected]",
  "name": "\u674e\u8302",
  "password": "111111",
  "phone": "13800001111",
  "pinned": []
}

转换为json字典对象变量

搜:

swift json parse string to dict

参考:

swift – How to convert a JSON string to a dictionary? – Stack Overflow
Convert Dictionary to JSON in Swift – Stack Overflow
先去自己试试。
搞懂了之后,再去用别人的库:
然后用下面代码:
func testJsonDecode() {

    let respJsonStr:String = "" +
        "{" +
        "\"active\": true," +
        "\"contacts\": []," +
        "\"doc_type\": \"user\"," +
        "\"email\": \"[email protected]\"," +
        "\"name\": \"\\u674e\\u8302\"," +
        "\"password\": \"111111\"," +
        "\"phone\": \"xxx\"," +
        "\"pinned\": []" +
    "}"
    print("respJsonStr=\(respJsonStr)")

    do{
        let respJsonData:NSData = respJsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
        print("respJsonData=\(respJsonData)")
        //        let decodedJsonDict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(respJsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        let decodedJsonDict:[String:AnyObject] = try NSJSONSerialization.JSONObjectWithData(respJsonData, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
        print("decodedJsonDict=\(decodedJsonDict)")
        /*
        decodedJsonDict=["active": 1, "phone": xxx, "password": 111111, "pinned": (
        ), "contacts": (
        ), "doc_type": user, "email": [email protected], "name": 李茂]
        */

    }catch let decodeJsonErr as NSError {
        print("decodeJsonErr=\(decodeJsonErr)")
    }
}

然后继续想办法测试每个项的类型:

        print(String(decodedJsonDict["active"].dynamicType)) //Optional<AnyObject>
        print(String(decodedJsonDict["phone"].dynamicType)) //Optional<AnyObject>
没办法,是因为前面强制了:[String:AnyObject]
所以都是:AnyObject
然后换成:
        print(String((decodedJsonDict["active"] as! Bool ).dynamicType)) //Bool
        print(String((decodedJsonDict["phone"] as! String).dynamicType)) //String
然后可以去用别人的库了:
先去试试SwiftyJSON
很好用:
func testJsonDecode() {

    let respJsonStr:String = "" +
        "{" +
        "\"active\": true," +
        "\"contacts\": [" +
        "\"contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e\"," +
        "\"contact-351e6499-142b-4d89-bf79-0f756ee41a32\"," +
        "\"contact-39ee1299-4e29-43cf-904f-d8826ce1b899\"" +
        "]," +

        "\"doc_type\": \"user\"," +
        "\"email\": \"[email protected]\"," +
        "\"name\": \”x\"," +
        "\"password\": \"111111\"," +
        "\"phone\": \"13811112222\"," +
        "\"pinned\": []" +
    "}"
    print("respJsonStr=\(respJsonStr)")

    let respJsonData:NSData = respJsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    print("respJsonData=\(respJsonData)")
    let decodedJsonDict = JSON(data: respJsonData)
    print("decodedJsonDict=\(decodedJsonDict)")
    /*
        decodedJsonDict={
        "active" : true,
        "phone" : "13811112222",
        "pinned" : [

        ],
        "password" : "111111",
        "contacts" : [
        "contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e",
        "contact-351e6499-142b-4d89-bf79-0f756ee41a32",
        "contact-39ee1299-4e29-43cf-904f-d8826ce1b899"
        ],
        "doc_type" : "user",
        "email" : "[email protected]",
        "name" : "x"
        }
    */

    let isActive:Bool = decodedJsonDict["active"].bool!
    print("isActive=\(isActive)") //isActive=true

    let name:String = decodedJsonDict["name"].string!
    print("name=\(name)") //name=CrifanLi

    let email:String = decodedJsonDict["email"].string!
    print("email=\(email)") //[email protected]

    let contactList:[String] = decodedJsonDict["contacts"].arrayObject as! [String]
    print("contactList=\(contactList)") //contactList=["contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e", "contact-351e6499-142b-4d89-bf79-0f756ee41a32", "contact-39ee1299-4e29-43cf-904f-d8826ce1b899"]
}
 即可。

转载请注明:在路上 » [已解决]swift 将json字符串转换为json字典变量

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.203 seconds, using 22.03MB memory