如何从iOS中的这些json对象创build一个json数组

我有一本像这样的字典。

NSDictionary *dict = @{@"cpu" : self.proData , @"date" : timeMilliString, @"memory" : self.memData, @"battery" : self.batData, @"deviceID" : @"1" }; 

我从这样创buildjson对象:

 self.jsonObj1 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; self.jsonObj2 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; self.jsonObj3 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; 

之后,我想把3个json对象放到一个json数组中,然后把这个json数组放到另一个json对象中。 最后,它应该看起来像这样:

 {"mobileData":[ { "cpu":-991, "date":"142441374.5834", "memory":978, "battery":-96, "deviceID" : 2 }, { "cpu":-51, "date":"142441374.5834", "memory":978, "battery":-96, "deviceID" : 2 }, { "cpu":-51, "date":"142441374.5834", "memory":978, "battery":-96, "deviceID" : 2 } ] } 

我已经尝试了如下,但它不工作。

 NSArray *jsonArray = @[self.jsonObj1, self.jsonObj2, self.jsonObj3]; NSDictionary *dict = @{@"mobileData" : jsonArray}; if ([NSJSONSerialization isValidJSONObject:dict]) { // Serialize the dictionary json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error2]; // If no errors, let's view the JSON if (json != nil && error2 == nil) { NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]; NSLog(@"JSON: %@", jsonString); //[jsonString release]; } } 

我得到一个例外。

有任何想法吗? 谢谢。

首先将所有字典添加到数组中。

 NSMutableArray *mutArrData = [NSMutableArray array]; //Add dictionaries which vary to your requirement. [mutArrData addObject:yourDictionary]; //1 [mutArrData addObject:yourDictionary]; //2 [mutArrData addObject:yourDictionary]; //3 

现在创build一个主字典来添加数组。

 NSDictionary *dictJsonData = [NSDictionary dictionaryWithObjectsAndKeys:[mutArrData mutableCopy],@"mobileData",nil]; 

现在从字典中创buildjson

 NSError *error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJsonData options:NSJSONWritingPrettyPrinted error:&error]; if (jsonData && !error) { NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"JSON: %@", jsonString); }