我有这样的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
得到结果: 1 或 0 。
if (x == 1)
{
mybutton.enabled = TRUE;
}
else
{
mybutton.enabled = FALSE;
}
我怎么做?
答案 0 :(得分: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,当您发送NO
时,它将始终评估为-boolValue
。
最后,上面的代码是为ARC编写的,需要Xcode 4.5或Clang 4.1以及iOS 5.0的部署目标。如果您不使用ARC,使用旧版Xcode构建,或者使用5.0之前的版本,则必须调整代码。
答案 1 :(得分:0)
答案 2 :(得分:0)
您所拥有的是NSArray
NSDictionary
。因此,使用SBJSON库可以执行以下操作
SBJsonParser *parser = [SBJsonParser alloc] init];
NSArray *data = [parser objectFromString:youJson];
for (NSDictionary *d in data)
{
NSString *value = [d objectForKey:@"Name"];
}
找到该库
答案 3 :(得分:0)
如果您想从JSON数据获取Dictionary的数据,请使用以下代码..
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/