Objective-C的JSON弄乱了我的阵列

时间:2011-08-01 21:22:25

标签: objective-c json xcode4

这是一个奇怪的错误,我不确定我是否正确使用JSON。当我从服务器获得一个具有正确数组的响应时,JSON会将其咀嚼起来,将大部分值转为零,我认为它也可能被密钥遗忘。

2011-08-01 16:08:15.981 My Alerts[2746:b303] From Server: {"cycleStart":"May 1, 2011","cycleEnds":"May 29, 2011","avg_usage":0,"estimate":0,"totalBudget":0,"Usage":0,"Cost":0}
2011-08-01 16:08:15.982 My Alerts[2746:b303] After JSON: (
   0,
   0,
   0,
   0,
   "May 29, 2011",
   "May 1, 2011",
   0
)

以下是我的代码,显示了JSON的使用位置。

NSString *post = [NSString stringWithFormat:@"username=%@&acct=%@", username, account];
NSLog(@"POST: %@", post);
NSData *postData = [NSData dataWithBytes: [post UTF8String] length: [post length]];

// Submit login data
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString: @"http://***.****.***/file1.php"]];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
[request setHTTPBody: postData];

// Retreive server response
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (returnData == nil) {
    NSLog(@"ERROR: %@", err);
}

NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSLog(@"From Server: %@", content); // <---JSON string returned perfectly from server

if (content != @"FAIL")
{
    NSArray *viewDetail = [[NSArray alloc] init];
    viewDetail = [[[content JSONValue] allValues] mutableCopy]; // <--JSON appears to be chewing it up
    NSLog(@"After JSON: %@", viewDetail); // <--Array is now messed up here.

    // Do stuff with viewDetail array

    [viewDetail release];
}

2 个答案:

答案 0 :(得分:2)

我看不出有什么问题。你想要allValues,你得到了所有的价值。除了排序之外,“从服务器”和“在JSON之后”是等效的。

排序不存在,因为NSDictionary(我相信你的JSONValue返回)不保证订单。并且密钥不在那里,因为您没有请求密钥,您请求了值。

如果你想要密钥,那就是allKeys方法。如果您想要特定值,则可以objectForKey:valueForKey:。您还可以使用各种枚举器。例如,我认为这应该有效:

NSDictionary *dict = [content JSONValue];
for (id key in dict) {
    NSLog(@"key: %@   value:%@", key, [dict objectForKey:key]);
}

答案 1 :(得分:0)

JSON没有咀嚼任何东西 - 实际上,你的大多数值都是0.你不使用普通数组,而是使用键值对。在Objective-C中,这些变为NSDictionary