【问题标题】:Converting NSString to NSDictionary / JSON将 NSString 转换为 NSDictionary / JSON
【发布时间】:2013-09-15 04:28:03
【问题描述】:

我将以下数据保存为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

谁能提出问题所在?

【问题讨论】:

  • 请注意,这里给定的json字符串“ID”是值,而不是键。
  • NSLog(@"JSON IS %@", json);??????

标签: objective-c xcode json nsstring nsdictionary


【解决方案1】:

我相信您误解了键值的 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;
}

希望这有助于获得清晰的理解。

【讨论】:

  • 不是真正的问题的答案,因为你告诉这个人重新格式化他们的字符串。在某些情况下(例如,iOS6 格式的 IAP 收据),您会收到此格式的字符串。
  • 即使是已接受答案的问题,您也可以随时发布答案。因此,请尽快发布您的答案版本并联系 OP 以考虑修改已接受的答案。 :)
  • BTW OP 已发布 JSON?您确定吗?请检查 OP 的要求,是否可以在该格式内实现?如果是,请回答问题,我将投票并创建新的赏金并将其奖励给您。
【解决方案2】:

我认为您从响应中获取数组,因此您必须将响应分配给数组。

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

【讨论】:

    【解决方案3】:

    使用此代码,其中 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
    }
    

    【讨论】:

    • [arr count] 返回零。
    • ERROR is Error Domain=NSCocoaErrorDomain Code=3840 "The operation could not be completed. (Cocoa error 3840.)" (JSON 文本没有以数组或对象开头,并且允许未设置片段的选项.) UserInfo=0x1f5b3660 {NSDebugDescription=JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。}
    • 您的 json 数据格式不正确
    【解决方案4】:

    斯威夫特 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)
        }
    }
    

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多