如何将 JSON 字符串反序列化为 NSDictionary?(适用于 iOS 5+)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8606444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)
提问by Andreas
In my iOS 5 app, I have an NSString
that contains a JSON string. I would like to deserialize that JSON string representation into a native NSDictionary
object.
在我的 iOS 5 应用程序中,我有一个NSString
包含 JSON 字符串的。我想将该 JSON 字符串表示反序列化为本机NSDictionary
对象。
"{\"password\" : \"1234\", \"user\" : \"andreas\"}"
I tried the following approach:
我尝试了以下方法:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:@"{\"2\":\"3\"}"
options:NSJSONReadingMutableContainers
error:&e];
But it throws the a runtime error. What am I doing wrong?
但它会引发运行时错误。我究竟做错了什么?
-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c'
回答by Abizern
It looks like you are passing an NSString
parameter where you should be passing an NSData
parameter:
看起来您正在传递一个NSString
应该传递NSData
参数的参数:
NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
回答by Desert Rose
NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
For example you have a NSString
with special characters in NSString
strChangetoJSON.
Then you can convert that string to JSON response using above code.
例如,您NSString
在NSString
strChangetoJSON 中有一个带有特殊字符的。然后您可以使用上述代码将该字符串转换为 JSON 响应。
回答by Hemang
I've made a category from @Abizern answer
我从@Abitern 回答中创建了一个类别
@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
NSError *error;
NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
return (!json ? nil : json);
}
@end
Use it like this,
像这样使用它,
NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);
回答by Imanou Petit
With Swift 3 and Swift 4, String
has a method called data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
has the following declaration:
在 Swift 3 和 Swift 4 中,String
有一个名为data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
有以下声明:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Returns a Data containing a representation of the String encoded using a given encoding.
返回包含使用给定编码编码的字符串表示的数据。
With Swift 4, String
's data(using:allowLossyConversion:)
can be used in conjunction with JSONDecoder
's decode(_:from:)
in order to deserialize a JSON string into a dictionary.
在 Swift 4 中,String
'sdata(using:allowLossyConversion:)
可以与JSONDecoder
's结合使用decode(_:from:)
,以便将 JSON 字符串反序列化为字典。
Furthermore, with Swift 3 and Swift 4, String
's data(using:allowLossyConversion:)
can also be used in conjunction with JSONSerialization
's json?Object(with:?options:?)
in order to deserialize a JSON string into a dictionary.
此外,在 Swift 3 和 Swift 4 中,String
'sdata(using:allowLossyConversion:)
也可以与JSONSerialization
's结合使用json?Object(with:?options:?)
,以便将 JSON 字符串反序列化为字典。
#1. Swift 4 solution
#1. 斯威夫特 4 解决方案
With Swift 4, JSONDecoder
has a method called decode(_:from:)
. decode(_:from:)
has the following declaration:
在 Swift 4 中,JSONDecoder
有一个名为decode(_:from:)
. decode(_:from:)
有以下声明:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Decodes a top-level value of the given type from the given JSON representation.
从给定的 JSON 表示中解码给定类型的顶级值。
The Playground code below shows how to use data(using:allowLossyConversion:)
and decode(_:from:)
in order to get a Dictionary
from a JSON formatted String
:
下面的 Playground 代码显示了如何使用data(using:allowLossyConversion:)
并从 JSON 格式中decode(_:from:)
获取 a :Dictionary
String
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
#2. Swift 3 and Swift 4 solution
#2. Swift 3 和 Swift 4 解决方案
With Swift 3 and Swift 4, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
在 Swift 3 和 Swift 4 中,JSONSerialization
有一个名为json?Object(with:?options:?)
. json?Object(with:?options:?)
有以下声明:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
从给定的 JSON 数据返回一个 Foundation 对象。
The Playground code below shows how to use data(using:allowLossyConversion:)
and json?Object(with:?options:?)
in order to get a Dictionary
from a JSON formatted String
:
下面的 Playground 代码显示了如何使用data(using:allowLossyConversion:)
并从 JSON 格式中json?Object(with:?options:?)
获取 a :Dictionary
String
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}
回答by IOS Singh
Using Abizerncode for swift 2.2
使用Abilern代码进行 swift 2.2
let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)