如何将JSON字符串转换为字典?

如何将JSON字符串转换为字典?

我想在我的快速项目中创建一个函数,将字符串转换为Dicaryjson格式,但我有一个错误:

无法转换表达式的类型(@lvalue NSData,Options:IntegerLitralConverable)

这是我的密码:

func convertStringToDictionary (text:String) -> Dictionary<String,String> {

    var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
    var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
    return json}

我在目标C中提出了这一职能:

- (NSDictionary*)convertStringToDictionary:(NSString*)string {
  NSError* error;
  //giving error as it takes dic, array,etc only. not custom object.  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  return json;}


慕丝7291255
浏览 1564回答 3
3回答

摇曳的蔷薇

SWIFT 3func&nbsp;convertToDictionary(text:&nbsp;String)&nbsp;->&nbsp;[String:&nbsp;Any]?&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;let&nbsp;data&nbsp;=&nbsp;text.data(using:&nbsp;.utf8)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;try&nbsp;JSONSerialization.jsonObject(with:&nbsp;data,&nbsp;options:&nbsp;[])&nbsp;as?&nbsp;[String:&nbsp;Any] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(error.localizedDescription) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil}let&nbsp;str&nbsp;=&nbsp;"{\"name\":\"James\"}"let&nbsp;dict&nbsp;=&nbsp;convertToDictionary(text:&nbsp;str)SWIFT 2func&nbsp;convertStringToDictionary(text:&nbsp;String)&nbsp;->&nbsp;[String:AnyObject]?&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;let&nbsp;data&nbsp;=&nbsp;text.dataUsingEncoding(NSUTF8StringEncoding)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;try&nbsp;NSJSONSerialization.JSONObjectWithData(data,&nbsp;options:&nbsp;[])&nbsp;as?&nbsp;[String:AnyObject] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;catch&nbsp;let&nbsp;error&nbsp;as&nbsp;NSError&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(error) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil}let&nbsp;str&nbsp;=&nbsp;"{\"name\":\"James\"}"let&nbsp;result&nbsp;=&nbsp;convertStringToDictionary(str)原始SWIFT 1答案:func&nbsp;convertStringToDictionary(text:&nbsp;String)&nbsp;->&nbsp;[String:String]?&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;let&nbsp;data&nbsp;=&nbsp;text.dataUsingEncoding(NSUTF8StringEncoding)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;error:&nbsp;NSError? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;json&nbsp;=&nbsp;NSJSONSerialization.JSONObjectWithData(data,&nbsp;options:&nbsp;NSJSONReadingOptions.allZeros,&nbsp;error:&nbsp;&error)&nbsp;as?&nbsp;[String:String] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;error&nbsp;!=&nbsp;nil&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;println(error) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;json&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil}let&nbsp;str&nbsp;=&nbsp;"{\"name\":\"James\"}"let&nbsp;result&nbsp;=&nbsp;convertStringToDictionary(str) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;["name":&nbsp;"James"]if&nbsp;let&nbsp;name&nbsp;=&nbsp;result?["name"]&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;The&nbsp;`?`&nbsp;is&nbsp;here&nbsp;because&nbsp;our&nbsp;`convertStringToDictionary`&nbsp;function&nbsp;returns&nbsp;an&nbsp;Optional&nbsp;&nbsp;&nbsp;&nbsp;println(name)&nbsp;//&nbsp;"James"}在您的版本中,您没有将适当的参数传递给NSJSONSerialization忘了投结果。另外,最好检查一下可能的错误。最后注意:只有当您的值是字符串时,这才有效。如果它可以是另一种类型,最好这样声明字典转换:let&nbsp;json&nbsp;=&nbsp;NSJSONSerialization.JSONObjectWithData(data,&nbsp;options:&nbsp;NSJSONReadingOptions.allZeros,&nbsp;error:&nbsp;&error)&nbsp;as?&nbsp;[String:AnyObject]当然,您还需要更改函数的返回类型:func&nbsp;convertStringToDictionary(text:&nbsp;String)&nbsp;->&nbsp;[String:AnyObject]?&nbsp;{&nbsp;...&nbsp;}

30秒到达战场

我更新了埃里克·D的答案SWIFT 2:func&nbsp;convertStringToDictionary(text:&nbsp;String)&nbsp;->&nbsp;[String:AnyObject]?&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;let&nbsp;data&nbsp;=&nbsp;text.dataUsingEncoding(NSUTF8StringEncoding)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;json&nbsp;=&nbsp;try&nbsp;NSJSONSerialization.JSONObjectWithData(data,&nbsp;options:&nbsp;.MutableContainers)&nbsp;as?&nbsp;[String:AnyObject] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;json&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print("Something&nbsp;went&nbsp;wrong") &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil}

偶然的你

JSONSerialization有一个名为jsonObject(with:options:).&nbsp;jsonObject(with:options:)有以下声明:class&nbsp;func&nbsp;jsonObject(with&nbsp;data:&nbsp;Data,&nbsp;options&nbsp;opt:&nbsp;JSONSerialization.ReadingOptions&nbsp;=&nbsp;[])&nbsp;throws&nbsp;->&nbsp;Any从给定的JSON数据返回Foundation对象。当你使用jsonObject(with:options:),您必须处理错误处理(try,&nbsp;try?或try!)和类型铸造(来自Any)。因此,您可以使用以下模式之一解决问题。#1.使用抛出并返回非可选类型的方法。import&nbsp;Foundationfunc&nbsp;convertToDictionary(from&nbsp;text:&nbsp;String)&nbsp;throws&nbsp;->&nbsp;[String:&nbsp;String]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;guard&nbsp;let&nbsp;data&nbsp;=&nbsp;text.data(using:&nbsp;.utf8)&nbsp;else&nbsp;{&nbsp;return&nbsp;[:]&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;anyResult:&nbsp;Any&nbsp;=&nbsp;try&nbsp;JSONSerialization.jsonObject(with:&nbsp;data,&nbsp;options:&nbsp;[]) &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;anyResult&nbsp;as?&nbsp;[String:&nbsp;String]&nbsp;??&nbsp;[:]}用法:let&nbsp;string1&nbsp;=&nbsp;"{\"City\":\"Paris\"}"do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;dictionary&nbsp;=&nbsp;try&nbsp;convertToDictionary(from:&nbsp;string1) &nbsp;&nbsp;&nbsp;&nbsp;print(dictionary)&nbsp;//&nbsp;prints:&nbsp;["City":&nbsp;"Paris"]}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;print(error)}let&nbsp;string2&nbsp;=&nbsp;"{\"Quantity\":100}"do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;dictionary&nbsp;=&nbsp;try&nbsp;convertToDictionary(from:&nbsp;string2) &nbsp;&nbsp;&nbsp;&nbsp;print(dictionary)&nbsp;//&nbsp;prints&nbsp;[:]}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;print(error)}let&nbsp;string3&nbsp;=&nbsp;"{\"Object\"}"do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;dictionary&nbsp;=&nbsp;try&nbsp;convertToDictionary(from:&nbsp;string3) &nbsp;&nbsp;&nbsp;&nbsp;print(dictionary)}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;print(error)&nbsp;//&nbsp;prints:&nbsp;Error&nbsp;Domain=NSCocoaErrorDomain&nbsp;Code=3840&nbsp;"No&nbsp;value&nbsp;for&nbsp;key&nbsp;in&nbsp;object&nbsp;around&nbsp;character&nbsp;9." &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserInfo={NSDebugDescription=No&nbsp;value&nbsp;for&nbsp;key&nbsp;in&nbsp;object&nbsp;around&nbsp;character&nbsp;9.}}#2.使用抛出并返回可选类型的方法import&nbsp;Foundationfunc&nbsp;convertToDictionary(from&nbsp;text:&nbsp;String)&nbsp;throws&nbsp;->&nbsp;[String:&nbsp;String]?&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;guard&nbsp;let&nbsp;data&nbsp;=&nbsp;text.data(using:&nbsp;.utf8)&nbsp;else&nbsp;{&nbsp;return&nbsp;[:]&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;anyResult:&nbsp;Any&nbsp;=&nbsp;try&nbsp;JSONSerialization.jsonObject(with:&nbsp;data,&nbsp;options:&nbsp;[]) &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;anyResult&nbsp;as?&nbsp;[String:&nbsp;String]}用法:let&nbsp;string1&nbsp;=&nbsp;"{\"City\":\"Paris\"}"do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;dictionary&nbsp;=&nbsp;try&nbsp;convertToDictionary(from:&nbsp;string1) &nbsp;&nbsp;&nbsp;&nbsp;print(String(describing:&nbsp;dictionary))&nbsp;//&nbsp;prints:&nbsp;Optional(["City":&nbsp;"Paris"])}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;print(error)}let&nbsp;string2&nbsp;=&nbsp;"{\"Quantity\":100}"do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;dictionary&nbsp;=&nbsp;try&nbsp;convertToDictionary(from:&nbsp;string2) &nbsp;&nbsp;&nbsp;&nbsp;print(String(describing:&nbsp;dictionary))&nbsp;//&nbsp;prints&nbsp;nil}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;print(error)}let&nbsp;string3&nbsp;=&nbsp;"{\"Object\"}"do&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;dictionary&nbsp;=&nbsp;try&nbsp;convertToDictionary(from:&nbsp;string3) &nbsp;&nbsp;&nbsp;&nbsp;print(String(describing:&nbsp;dictionary))}&nbsp;catch&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;print(error)&nbsp;//&nbsp;prints:&nbsp;Error&nbsp;Domain=NSCocoaErrorDomain&nbsp;Code=3840&nbsp;"No&nbsp;value&nbsp;for&nbsp;key&nbsp;in&nbsp;object&nbsp;around&nbsp;character&nbsp;9." &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserInfo={NSDebugDescription=No&nbsp;value&nbsp;for&nbsp;key&nbsp;in&nbsp;object&nbsp;around&nbsp;character&nbsp;9.}}#3.使用不抛出并返回非可选类型的方法。import&nbsp;Foundationfunc&nbsp;convertToDictionary(from&nbsp;text:&nbsp;String)&nbsp;->&nbsp;[String:&nbsp;String]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;guard&nbsp;let&nbsp;data&nbsp;=&nbsp;text.data(using:&nbsp;.utf8)&nbsp;else&nbsp;{&nbsp;return&nbsp;[:]&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;anyResult:&nbsp;Any?&nbsp;=&nbsp;try?&nbsp;JSONSerialization.jsonObject(with:&nbsp;data,&nbsp;options:&nbsp;[]) &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;anyResult&nbsp;as?&nbsp;[String:&nbsp;String]&nbsp;??&nbsp;[:]}用法:let&nbsp;string1&nbsp;=&nbsp;"{\"City\":\"Paris\"}"let&nbsp;dictionary1&nbsp;=&nbsp;convertToDictionary(from:&nbsp;string1)print(dictionary1)&nbsp;//&nbsp;prints:&nbsp;["City":&nbsp;"Paris"]let&nbsp;string2&nbsp;=&nbsp;"{\"Quantity\":100}"let&nbsp;dictionary2&nbsp;=&nbsp;convertToDictionary(from:&nbsp;string2)print(dictionary2)&nbsp;//&nbsp;prints:&nbsp;[:]let&nbsp;string3&nbsp;=&nbsp;"{\"Object\"}"let&nbsp;dictionary3&nbsp;=&nbsp;convertToDictionary(from:&nbsp;string3)print(dictionary3)&nbsp;//&nbsp;prints:&nbsp;[:]#4.使用不抛出并返回可选类型的方法import&nbsp;Foundationfunc&nbsp;convertToDictionary(from&nbsp;text:&nbsp;String)&nbsp;->&nbsp;[String:&nbsp;String]?&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;guard&nbsp;let&nbsp;data&nbsp;=&nbsp;text.data(using:&nbsp;.utf8)&nbsp;else&nbsp;{&nbsp;return&nbsp;nil&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;anyResult&nbsp;=&nbsp;try?&nbsp;JSONSerialization.jsonObject(with:&nbsp;data,&nbsp;options:&nbsp;[]) &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;anyResult&nbsp;as?&nbsp;[String:&nbsp;String]}用法:let&nbsp;string1&nbsp;=&nbsp;"{\"City\":\"Paris\"}"let&nbsp;dictionary1&nbsp;=&nbsp;convertToDictionary(from:&nbsp;string1)print(String(describing:&nbsp;dictionary1))&nbsp; //&nbsp;prints:&nbsp;Optional(["City":&nbsp;"Paris"])let&nbsp;string2&nbsp;=&nbsp;"{\"Quantity\":100}"let&nbsp;dictionary2&nbsp;=&nbsp;convertToDictionary(from:&nbsp;string2)print(String(describing:&nbsp;dictionary2))&nbsp; //&nbsp;prints:&nbsp;nillet&nbsp;string3&nbsp;=&nbsp;"{\"Object\"}"let&nbsp;dictionary3&nbsp;=&nbsp;convertToDictionary(from:&nbsp;string3)print(String(describing:&nbsp;dictionary3))&nbsp; //&nbsp;prints:&nbsp;nil
打开App,查看更多内容
随时随地看视频慕课网APP