您好我正在尝试将Json字符串解析为NSArray
并将某些结果保存为字符串,以便为我的应用中的不同用户设置权限。我目前的代码是:
NSError *jsonParsingError1 = nil;
accountData = [NSJSONSerialization JSONObjectWithData:jsonAccount
options:NSJSONReadingMutableContainers error:&jsonParsingError1];
accountData
是在.h文件中创建的NSMutableArray。
jsonAccount
是通过转换NSString
阵列的NSLog输出是;
{
account = "XXXX";
companyName = XXXXX;
id = XXXXX;
websites = (
{
account = "XXXXX";
accountId = XXXXX;
anonymiseIP = 0;
companyName = XXXXX;
XXXX = 0;
domains = (
"XXXXX"
);
features = {
advancedSegmentation = 1;
attentionHeatmaps = 1;
domains = 0;
dotHeatmaps = 1;
goalConversionTracking = 1;
interactionHeatmaps = 1;
leadInfo = 0;
scrollHeatmaps = 1;
timeHeatmaps = 1;
users = 0;
valueHeatmaps = 1;
visitorPlayback = 1;
visitorScoring = 1;
visitors = 1;
};
fixedElementSelector = "";
flagClicksReceived = 0;
flagDataReceived = 0;
flagGoalsReceived = 0;
flagInteractionsReceived = 0;
flagScrollsReceived = 0;
id = XXXXX;
interactionSelector = "";
name = "XXXX";
permissions = (
segments,
heatmaps,
visitors,
campaigns,
support,
globalSettings,
websiteSettings
);
setCookies = 1;
status = 1;
statusMessage = "";
statusString = OK;
trialling = 1;
}
);
},
当我尝试从其中一个结果创建一个sting并将其显示在日志中时,我收到此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray:]: unrecognized selector sent to instance 0x6a950f0'
如何将不同的密钥保存为字符串?
答案 0 :(得分:3)
看起来你的JSON是一个Dictionary而不是一个Array。
答案 1 :(得分:2)
您的JSON不是数组,您应该像NSDictionary一样解析它
答案 2 :(得分:2)
解析JSON后,您应该测试它返回的对象类型。 E.g:
if ([accountData isKindOfClass:[NSArray class]]) {
// handle like an array
} else if ([accountData isKindOfClass:[NSDictionary class]]) {
// handle like a dictionary
}
答案 3 :(得分:2)
您的JSON是一个包含四个键的字典:account,companyName,id和website。
关键"网站"会给你一个数组。
您可以遍历"网站"数组,每个元素都是字典。
"网站中的每个词典"数组有很多键,如account,accountId,anonymiseIP等。其中一些键具有字典或数组的值。
在NSLog语句中,(a,b,c)将是一个数组,而{a = x; b = y; c = z;将是一本字典。
答案 4 :(得分:1)
您的服务器响应是字典,因此将accountData更改为字典
在下面写下NSLog,你会在其中获得信息
[accountData objectForKey:@"account"];
[accountData objectForKey:@"companyName"];
[accountData objectForKey:@"id"];
[[accountData objectForKey:@"websites"] count];//array
[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"account"];
[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"domains"];
[[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"domains"]count]; //array
[[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"domains"]objectAtIndex:0];