如何从JSON响应中获取特定数据?

时间:2014-05-28 06:54:58

标签: objective-c

如何从JSON响应中获取特定数据?以下是我服务器的响应。得到A,B,C然后需要获得A.data值。

{
       response   =     (
                  {
              A =             (
                                {
                    data = "2014-05-21";            
                    name = "percent";               

                    );
                }
            );
            B =             (
                                {
                    data = "2014-05-23";            
                    name = "short";                  

                    );
                },
                                {
                    data = "2014-05-23";             
                    name = "mam";                    
                    );
                },
                                {
                    data = "2014-05-23";             
                    name = "sinh";                
                    );
                }
            );

1 个答案:

答案 0 :(得分:1)

到目前为止你尝试了什么?使用NSJSONSerialization有问题吗? 。只是旁注:始终使用isKindOfClass仔细检查从反序列化器接收的对象类型。

看起来像这样:

NSError *e = nil;
NSDictionary *responseDict = [NSJSONSerialization 
    JSONObjectWithData:data 
    options: NSJSONReadingMutableContainers 
    error: &e];
if ([responseDict isKindOfClass[NSDictionary class]]) {
    NSDictionary *abcDict = [responseDict objectForKey:@"response"];
    if (abcDict isKindOfClass [NSDictionary class]]) {
        NSDictionary *dataSetDict = [abcDict objectForKey:@"A"];
        if ([dataSetDict isKindOfClass:[NSDictionary class] {
            // Here it might get difficult. In case of the key A you get a dictionary but 
            // the key B will return an array of dictionaries. And even the data fields 
            // may vary. In your example you will have strings only but you better double check.
        }

    }
}

检查错误e,我没有。 并处理你很多人没有收到预期收到的情况。所以添加else语句并处理问题,抛出并捕获异常左右。