Kevin Kohler
Kevin Kohler

Reputation: 364

NSJSONSerialization Json Formatting

So I have an array I wanna convert to nsdictionary. My process works great but I would like to add a heading to the json string.

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);

Below outputs :

{[
  {
    "Showid" : "10027"
  },
  {
    "Showid" : "10707"
  },
  {
    "Showid" : "10759"
  }.....

]

How do I make it look like this

{
    "Shows":[
  {
    "Showid" : "10027"
  },
  {
    "Showid" : "10707"
  },
  {
    "Showid" : "10759"
  }....
]
}

Upvotes: 2

Views: 2615

Answers (2)

lakshmen
lakshmen

Reputation: 29064

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

Since your jsonstring is a string, you can change it.

hope this helps..

EDIT:

NSString *jsonString1 = [NSString stringWithFormat:@"{"Shows":%@}",jsonString];

Upvotes: 3

Sulthan
Sulthan

Reputation: 130072

Just add your array into a dictionary with the correct key.

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

Upvotes: 2

Related Questions