SoFunction
Updated on 2025-03-03

Methods of converting dictionary and JSON in Swift

Swift often encounters mutual conversion between dictionaries and strings, so it can be converted and encapsulated. The conversion code is as follows:

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
  if let data = (using: .utf8) {
    do {
      return try (with: data, options: [(rawValue: 0)]) as? [String:AnyObject]
    } catch let error as NSError {
      print(error)
    }
  }
  return nil
}


func convertDictionaryToString(dict:[String:AnyObject]) -> String {
  var result:String = ""
  do {
    //If options is set, the print format will be better read    let jsonData = try (withJSONObject: dict, options: (rawValue: 0))

    if let JSONString = String(data: jsonData, encoding: .utf8) {
      result = JSONString
    }

  } catch {
    result = ""
  }
  return result
}

func convertArrayToString(arr:[AnyObject]) -> String {
  var result:String = ""
  do {
    let jsonData = try (withJSONObject: arr, options: (rawValue: 0))

    if let JSONString = String(data: jsonData, encoding: .utf8) {
      result = JSONString
    }

  } catch {
    result = ""
  }
  return result
}

Actual test:

 

  let jsonText:String = "{\"order_info\":[{\"order_id\":\"1479828084819597144\",\"channel\":\"ios\",\"product_id\":\"02\"},{\"order_id\":\"1479828084819597144\",\"channel\":\"ios\",\"product_id\":\"02\"}]}"

  let dict = (text: jsonText)
  print("Dictionary after string conversion:\(dict!)")


  var dictionaryOrArray : [String: AnyObject] = [:]
  dictionaryOrArray["a\"b"] = "cd" as AnyObject?
  dictionaryOrArray["strings"] = ["string", "another"] as AnyObject?
  dictionaryOrArray["keywdict"] = [ "anotherKey": 100, "Key2": "Val2"] as AnyObject?
  dictionaryOrArray["numbers"] = [ 1, 2, 3] as AnyObject?
  dictionaryOrArray["bools"] = [ true, false] as AnyObject?
  let convertResult:String = (dict: dictionaryOrArray)
  print("A string after a dictionary conversion:\(convertResult)")


  let array:[String] = ["FlyElephant","keso"]
  print("Array after array conversion:\((arr: array as [AnyObject]))")

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.