2013-02-14 60 views
2

所以我有一个数组我想转换为nsdictionary。我的过程很好,但我想为json字符串添加一个标题。NSJSONSerialization 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" 
    }.... 
] 
} 
+0

顺便说一下,'NSJSONReadingMutableContainers'不允许用于这种方法,您正在编写,而不是读取。 – Sulthan 2013-02-14 19:13:38

回答

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]; 
3
NSMutableString *jsonString1 = [[@"{Shows:[" stringByAppendingString:jsonString] stringByAppendingString:@"]}"]; 

由于您的jsonstring是一个字符串,你可以改变它。

希望这有助于..

编辑:

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

你最后还是遗漏了括号。 :)我仍然可以发布一个字符串到一个httprequest像[request setHTTPBody:jsonString]; – 2013-02-14 16:50:49

+0

谢谢,先生! – 2013-02-14 16:56:23

+0

没问题..高兴的是它有帮助... – lakesh 2013-02-14 16:58:12