Pet*_*ter 5 api json objective-c nsdictionary cpanel
我目前正在尝试使用json和objective-c但是有点困难.以下是返回的json
{
sethostname = (
{
msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
status = 1;
statusmsg = "Hostname Changed to: a.host.name.com";
warns = (
);
});
}
Run Code Online (Sandbox Code Playgroud)
我能够检查响应是否会返回并且密钥是sethostname但是无论我尝试什么,我都无法获得例如status或statusmsg的值.任何人都可以指出我在正确的位置.以下是我用来检查是否返回sethostname的基本代码.
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
NSLog([res description]);
NSArray *arr;
arr = [res allKeys];
if ([arr containsObject:@"sethostname"])
{
NSLog(@"worked");
}
Run Code Online (Sandbox Code Playgroud)
小智 11
如有疑问,请记下JSON数据的结构.例如:
{
sethostname = (
{
msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
status = 1;
statusmsg = "Hostname Changed to: a.host.name.com";
warns = (
);
});
}
Run Code Online (Sandbox Code Playgroud)
(实际上是NeXTSTEP属性列表格式)意味着你有一个顶级字典.此顶级字典包含一个名为sethostname其数组的键.这个数组由字典组成,每个字典都有一组键:msgs, status, statusmsg, warns.msgs有一个字符串值,status有一个数值,statusmsg有一个字符串值,警告`有一个数组值:
dictionary (top-level)
sethostname (array of dictionaries)
dictionary (array element)
msgs (string)
status (number)
statusmsg (string)
warns (array)
??? (array element)
Run Code Online (Sandbox Code Playgroud)
理解了这个结构后,您的代码应如下所示:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
if (!res) { // JSON parser failed }
// dictionary (top-level)
if (![res isKindOfClass:[NSDictionary class]]) {
// JSON parser hasn't returned a dictionary
}
// sethostname (array of dictionaries)
NSArray *setHostNames = [res objectForKey:@"sethostname"];
// dictionary (array element)
for (NSDictionary *setHostName in setHostNames) {
// status (number)
NSNumber *status = [setHostName objectForKey:@"status"];
// statusmsg (string)
NSString *statusmsg = [setHostName objectForKey:@"statusmsg"];
…
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11281 次 |
| 最近记录: |