Convert Json string to Json object in Swift 4

后端 未结 4 1193
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 06:13

I try to convert JSON string to a JSON object but after JSONSerialization the output is nil in JSON.

Response String:

[{\\\         


        
4条回答
  •  春和景丽
    2020-12-08 06:59

    I used below code and it's working fine for me. :

    let jsonText = "{\"userName\":\"Bhavsang\"}"
    var dictonary:NSDictionary?
        
    if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
            
         do {
                dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
            
                if let myDictionary = dictonary
                  {
                      print(" User name is: \(myDictionary["userName"]!)")
                  }
                } catch let error as NSError {
                
                print(error)
             }
    }
    

提交回复
热议问题