2012-10-03 52 views
0

我有JSON是这样的:从JSON数据如何获得数据

[{"ID" : "351", "Name" : "Cam123 ", "camIP" : "xxx.xxx.xxx.xxx", 
    "Username" : "admin", "Password" : "damin", "isSupportPin" : "1" }, 
{"ID" : "352", "Name" : "Cam122 ", "camIP" : "xxx.xxx.xxx.xxx", 
    "Username" : "admin", "Password" : "damin", "isSupportPin" : "0" } 
] 

我想isSupportPin与结果:或。

if (x == 1) 
{ 
    mybutton.enabled = TRUE; 
} 
else 
{ 
    mybutton.enabled = FALSE; 
} 

我该怎么做?

+0

我认为你想将JSON数据转换成字典.am我对吗? –

回答

0

这里,你有什么是NSDictionary秒的NSArray。因此,使用SBJSON库,你可以做如下

SBJsonParser *parser = [SBJsonParser alloc] init]; 
NSArray *data = [parser objectFromString:youJson]; 
for (NSDictionary *d in data) 
{ 
    NSString *value = [d objectForKey:@"Name"]; 
} 

库可以在http://stig.github.com/json-framework/

+1

除非您需要定位iOS的旧版本,否则最好使用较新的Foundation类进行JSON序列化。它们速度非常快,它们在Foundation中可用,没有意外,它们不会添加可能会使调试更困难的类别,并且它们遵循与所有其他Foundation序列化类完全相同的模式,这意味着一旦您了解了模式,您可以相对容易地序列化/反序列化属性列表,符合NSCoding的类,JSON数据等。 –

+0

你可以称我老派;)但优点。我们的客户通常至少需要iOS 4.3。 – tGilani

+0

是的,我为我们的任何需要非iOS 5的代码所做的第一件事情之一就是动态地添加此类并将其归入外部JSON库,但至少这样一切仍然使​​用新的模式,以及任何运行iOS 5+的东西直接使用新类:) –

1

找到假设你有这个数据,它的NSData对象:

// Your JSON is an array, so I'm assuming you already know 
// this and know which element you need. For the purpose 
// of this example, we'll assume you want the first element 
NSData* jsonData = /* assume this is your data from somewhere */ 
NSError* error = nil; 
NSArray* array = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; 
if(!array) { 
    // there was an error with the structure of the JSON data... 
} 
if([array count] > 0) { 
    // we got our data in Foundation classes now... 
    NSDictionary* elementData = array[0]; // pick the correct element 
    // Now, extract the 'isSupportPin' attribute 
    NSNumber* isSupportPin = elementData[@"isSupportPin"]; 
    // Enable the button per this item 
    [mybutton setEnabled:[isSupportPin boolValue]]; 
} else { 
    // Valid JSON data, but no elements... do something useful 
} 

上面的示例代码代码片段假设你知道你想要读取哪个元素(我猜这些是用户行或其他东西),并且知道JSON属性名称是什么(例如,如果isSupportPin实际上没有在该数组中返回的JSON对象中定义,它无线我会简单地返回nil,当你发送它-boolValue时它总是评估为NO)。

最后,上面的代码是为ARC编写的,需要Xcode 4.5或Clang 4.1以及iOS 5.0的部署目标。如果您不使用ARC,使用Xcode的旧版本构建,或者定位5.0以前的版本,则必须调整代码。

+0

Hey Jason。您的JSON解析行似乎缺少NSJSONSerialization类的名称。不应该'NSArray * array = [JSONObjectWithData:jsonData options:0 error:&error]'实际上是'NSArray * array = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]'? –

+0

@MattLong你是对的!哎呀:)谢谢你的头!请随时编辑我的答案,以确保正确:) –

0

如果你想获得弗朗JSONData数据或字典然后用波纹管代码..

NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; 
NSArray *resultsArray = [responseString JSONValue]; 
for(NSDictionary *item in resultsArray) 
{ 
    NSDictionary *project = [item objectForKey:@"result"];//use your key name insted of result 
    NSLog(@"%@",project); 
} 

,并从下面的链接下载JSON库和教程...

http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/