【问题标题】:how to parse a JSON string in iphone Objective - C?如何在 iphone Objective-C 中解析 JSON 字符串?
【发布时间】:2011-10-27 23:12:24
【问题描述】:

您好,我正在尝试在 iphone 中解析 JSON 字符串,到目前为止,我已经能够正确获取 JSON VALUE

但在那之后我得到一个错误:

-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x62242e0
2011-08-16 16:11:58.792 BleepBleep[4083:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x62242e0'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x010a9be9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x011fe5c2 objc_exception_throw + 47
    2   CoreFoundation                      0x010ab6fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x0101b366 ___forwarding___ + 966
    4   CoreFoundation                      0x0101af22 _CF_forwarding_prep_0 + 50
    5   BleepBleep                          0x0000733f -[Screen1 network:didFinishLoadingWithRequest:data:] + 79
    6   BleepBleep                          0x0000b7e4 -[WNetwork handleResponse] + 323
    7   BleepBleep                          0x0000b69b -[WNetwork connectionDidFinishLoading:] + 36
    8   Foundation                          0x00077172 -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading] + 108
    9   Foundation                          0x000770cb _NSURLConnectionDidFinishLoading + 133
    10  CFNetwork                           0x01674606 _ZN19URLConnectionClient23_clientDidFinishLoadingEPNS_26ClientConnectionEventQueueE + 220
    11  CFNetwork                           0x0173f821 _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 293
    12  CFNetwork                           0x0166ae3c _ZN19URLConnectionClient13processEventsEv + 100
    13  CFNetwork                           0x0166acb7 _ZN17MultiplexerSource7performEv + 251
    14  CoreFoundation                      0x0108b01f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    15  CoreFoundation                      0x00fe928b __CFRunLoopDoSources0 + 571
    16  CoreFoundation                      0x00fe8786 __CFRunLoopRun + 470
    17  CoreFoundation                      0x00fe8240 CFRunLoopRunSpecific + 208
    18  CoreFoundation                      0x00fe8161 CFRunLoopRunInMode + 97
    19  GraphicsServices                    0x019de268 GSEventRunModal + 217
    20  GraphicsServices                    0x019de32d GSEventRun + 115
    21  UIKit                               0x002e442e UIApplicationMain + 1160
    22  BleepBleep                          0x00002018 main + 102
    23  BleepBleep                          0x00001fa9 start + 53
)
terminate called after throwing an instance of 'NSException'

这是我在 didFinishLoadingWithRequest 中使用的代码

-(void)network:(WNetwork*)network didFinishLoadingWithRequest:(NSInteger)pReq data:(NSMutableDictionary*)pData
{
    [self removeLoader];

    switch (pReq) {
        case JBJsonParser:
        {
            NSArray *parsedString = [pData objectForKey:@"placesname"];
            DLog(@"LIST %@",parsedString);
        }
    break;      
        default:
            break;
}

}

在网络类中我使用的是dis代码:

{
    SBJSON *parser = [SBJSON new];      
    NSString *dataString = [[NSString alloc] initWithData:mRespData encoding:NSUTF8StringEncoding];


    NSMutableDictionary *newDic = [dataString JSONValue];

    if ([(id)mDelegate respondsToSelector:@selector(network:didFinishLoadingWithRequest:data:)]) {
        [self.mDelegate network:self didFinishLoadingWithRequest:mReqType data:newDic];
    }
    [newDic autorelease];

    [dataString release];
    [parser release];
}

【问题讨论】:

标签: iphone objective-c json parsing sbjson


【解决方案1】:

一点点 JSON:

这是一个 JSON 数组

["firstValue", "secondValue"]

这是一个 JSON 字典

{
"A key" : "A value",
"Another key" : "Another value"
}

您的 JSON 告诉解析器根类型是 数组。因此,jsonValue 返回一个数组。 您正在尝试在该数组上调用 objectForKey (NSDictionary 方法)。这就是引发异常的原因。

请发布您的 JSON,以便我们查看结构以及您应该如何解析它。或者,尝试记录您存储 jsonValue 的对象。


更新:

阅读您的 JSON 后,您应该这样解析它:

NSString *jsonString; // set this to your json
NSArray *places = [jsonString jsonValue];
// then iterate through the places, saving off the bits you need
for (NSDictionary *place in places) {
    NSString *placeName = [place objectForKey:@"placesname"]; // for example
    NSLog(@"Name of place: %@", placeName); 
}

您可能想要做的是创建一个名为 place 的自定义类,该类具有 lat、long、placename 等属性,然后保存一个数组。

【讨论】:

  • 我应该使用 NSDictionary 方法还是数组并且应该是 NSArray *parsedString = [pData objectForKey:@"placesname"];或 NSDictionary *parsedString = [pData objectForKey:@"placesname"];
  • [ { “0”:“2”,“1”:“abc”,“2”:“12312343”,“3”:“123123”,“placesID”:“2”, “地名”:“abc”,“纬度”:“12312343”,“长”:“123123”},{“0”:“3”,“1”:“abc”,“2”:“12312343”, “3”:“123123”,“placesID”:“3”,“placesname”:“abc”,“Lat”:“12312343”,“long”:“123123”}]
  • 我替换了我的代码:NSArray *parsedString = [pData objectForKey:@"placesname"]; DLog(@"LIST %@",parsedString);和你的: NSString *jsonString; // 将此设置为您的 json NSArray *places = [jsonString jsonValue]; // 然后遍历这些地方,节省你需要的位 (NSDictionary *place in places) { NSString *placeName = [place objectForKey:@"placesname"]; // 例如 NSLog(@"地名: %@", placeName); } 现在应用程序崩溃,没有错误,对不起,我可能会问你最愚蠢的问题,但我在这方面有点新......
  • 使用断点我可以看到它在 [self.mDelegate network:self didFinishLoadingWithRequest:mReqType data:newDic] 上崩溃; ///////////////////////////////// in - (void) connectionDidFinishLoading:(NSURLConnection * )连接
【解决方案2】:

这个post 应该会有所帮助。

这里有一些很好的例子: http://iosdevelopertips.com/cocoa/json-framework-for-iphone-part-2.html

【讨论】:

    【解决方案3】:

    JSON 语法表示数组和字典。在解析“未知”的 JSON 代码时,您不知道给定的“洋葱层”是数组还是字典,因此您必须检查(在每个级别)以查看您拥有的对象类型。使用[myObject isKindOfClass:[NSArray class]][myObject isKindOfClass:[NSDictionary class]]

    即使使用“已知”的 JSON 源进行这种检查也不是不明智的,因为网站可能会中断或更改,最好提供一个很好的错误消息(并责怪网站)而不是让您的应用程序崩溃。

    【讨论】:

    • 不知道为什么这被否决了。这是一个准确而有用的回应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2018-09-18
    • 1970-01-01
    相关资源
    最近更新 更多