xcode 将NSString转换为NSDictionary / JSON

pbgvytdp  于 2022-12-24  发布在  其他
关注(0)|答案(5)|浏览(197)

我将以下数据保存为NSString

{
    Key = ID;
    Value =         {
        Content = 268;
        Type = Text;
    };
},
    {
    Key = ContractTemplateId;
    Value =         {
        Content = 65;
        Type = Text;
    };
},

我希望将此数据转换为包含键值对的NSDictionary
我首先尝试将NSString转换为JSON对象,如下所示:

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

然而,当我尝试:

NSString * test = [json objectForKey:@"ID"];
NSLog(@"TEST IS %@", test);

我收到的值为NULL
有谁能指出问题出在哪里吗?

h4cxqtbf

h4cxqtbf1#

我认为您误解了JSON格式的键值。

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

现在,如果执行以下NSLog语句

NSLog(@"%@",[json objectForKey:@"ID"]);

结果将是另一个NSDictionary。

{
    Content = 268;
    type = text;
}
2o7dmzc5

2o7dmzc52#

我认为你从response中得到了数组所以你必须把response赋给数组。

NSError *err = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:@"ID"];
NSLog(@"Test is %@",test);
jjjwad0x

jjjwad0x3#

使用以下代码,其中str是JSON字符串:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}
wf82jlnq

wf82jlnq4#

雨燕3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}
jq6vz3qz

jq6vz3qz5#

使用以下代码从AFHTTPSessionManager故障块获取响应对象;然后你可以将泛型类型转换成所需的数据类型:

id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];

相关问题