所以我有一个数组想转换为nsdictionary。我的过程效果很好,但我想向json字符串添加标题。

NSArray *showarray = [[MMIStore defaultStore] loadAllShows ];
NSMutableArray* jsonArray = [[NSMutableArray alloc] init];

for (Show* show in showarray) {
    NSMutableDictionary* showDictionary = [[NSMutableDictionary alloc] init];
    [showDictionary setObject:show.showid forKey:@"Showid"];
    [jsonArray addObject:showDictionary];
}
NSData* nsdata = [NSJSONSerialization dataWithJSONObject:jsonArrayoptions:NSJSONReadingMutableContainers error:nil];
NSString* jsonString =[[NSString alloc] initWithData:nsdata encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);

输出如下:
{[
  {
    "Showid" : "10027"
  },
  {
    "Showid" : "10707"
  },
  {
    "Showid" : "10759"
  }.....

]

我如何使它看起来像这样
{
    "Shows":[
  {
    "Showid" : "10027"
  },
  {
    "Showid" : "10707"
  },
  {
    "Showid" : "10759"
  }....
]
}

最佳答案

只需使用正确的键将数组添加到字典中即可。

NSArray *showarray = [[MMIStore defaultStore] loadAllShows];
NSMutableArray* jsonShowsArray = [[NSMutableArray alloc] init];

for (Show* show in showarray) {
    NSMutableDictionary* showDictionary = [[NSMutableDictionary alloc] init];
    [showDictionary setObject:show.showid forKey:@"Showid"];
    [jsonShowsArray addObject:showDictionary];
}

NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:jsonShowsArray
                                                           forKey:@"Shows"]

NSData* nsdata = [NSJSONSerialization dataWithJSONObject:jsonDictionary
                                                 options:NSJSONReadingMutableContainers
                                                 error:nil];

关于ios - NSJSONSerialization Json格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14879403/

10-13 05:05