2

所以我有一个要转换为 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"
  }....
]
}
4

2 回答 2

3
NSMutableString *jsonString1 = [[@"{Shows:[" stringByAppendingString:jsonString] stringByAppendingString:@"]}"];

由于您的 jsonstring 是一个字符串,因此您可以更改它。

希望这可以帮助..

编辑:

NSString *jsonString1 = [NSString stringWithFormat:@"{"Shows":%@}",jsonString];
于 2013-02-14T16:31:43.787 回答
2

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

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];
于 2013-02-14T17:00:13.410 回答