如何在iOS中从这些json对象创建json数组

时间:2015-02-24 09:47:21

标签: ios iphone json

我有一本看起来像这样的字典。

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

我正在创建json对象,如下所示:

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];
            }
        }

我得到了例外。

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:2)

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

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

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

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

现在从字典

创建json
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);
}