如何将JSON字符串反序列化为NSDictionary?(适用于iOS 5+)

And*_*eas 151 json nsdictionary nsstring ios ios5

在我的iOS 5应用程序中,我有一个NSString包含JSON字符串的应用程序.我想将JSON字符串表示反序列化为本机NSDictionary对象.

 "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:@"{\"2\":\"3\"}"
                                options:NSJSONReadingMutableContainers
                                  error:&e];  
Run Code Online (Sandbox Code Playgroud)

但它会引发运行时错误.我究竟做错了什么?

-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c'
Run Code Online (Sandbox Code Playgroud)

Abi*_*ern 328

看起来你正在传递一个NSString参数,你应该传递一个NSData参数:

NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢Objective C.将您的字符串编码为原始字节,然后将它们解码回NSStrings和NSNumbers.这很明显,不是吗? (3认同)

Des*_*ose 36

NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error];
Run Code Online (Sandbox Code Playgroud)

例如NSString,NSStringstrChangetoJSON中有一个特殊字符.然后,您可以使用上面的代码将该字符串转换为JSON响应.


Hem*_*ang 5

我从@Abizern回答了一个类别

@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
Run Code Online (Sandbox Code Playgroud)

像这样使用它,

NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);
Run Code Online (Sandbox Code Playgroud)


Ima*_*tit 5

在 Swift 3 和 Swift 4 中,String有一个名为data(using:allowLossyConversion:). data(using:allowLossyConversion:)有以下声明:

func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Run Code Online (Sandbox Code Playgroud)

返回包含使用给定编码编码的字符串表示的数据。

在 Swift 4 中,String'sdata(using:allowLossyConversion:)可以与JSONDecoder's结合使用decode(_:from:),以便将 JSON 字符串反序列化为字典。

此外,在 Swift 3 和 Swift 4 中,String'sdata(using:allowLossyConversion:)也可以与JSONSerialization's结合使用json?Object(with:?options:?),以便将 JSON 字符串反序列化为字典。


#1. 斯威夫特 4 解决方案

在 Swift 4 中,JSONDecoder有一个名为decode(_:from:). decode(_:from:)有以下声明:

func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Run Code Online (Sandbox Code Playgroud)

从给定的 JSON 表示中解码给定类型的顶级值。

下面的 Playground 代码显示了如何使用data(using:allowLossyConversion:)并从 JSON 格式中decode(_:from:)获取 a :DictionaryString

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

#2. Swift 3 和 Swift 4 解决方案

在 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
Run Code Online (Sandbox Code Playgroud)

从给定的 JSON 数据返回一个 Foundation 对象。

下面的 Playground 代码显示了如何使用data(using:allowLossyConversion:)并从 JSON 格式中json?Object(with:?options:?)获取 a :DictionaryString

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)
    }
}
Run Code Online (Sandbox Code Playgroud)