0

我得到这样的 NSString

 [Hello] [;]
 [hi] [;]
 [Its there] [;]
 [Welcome] [;]
 [Hello] [;]

我想转换为 json 格式,我不知道如何将数据数组转换为 json。请帮我

4

1 回答 1

2

您需要使用以下代码。

NSDictionary *dict = [myJsonString JSONValue];

如果它不起作用,请使用以下

// 
// we begin with our string in json format
//
NSString *jsonString = [[NSString alloc] initWithString:@"{\"1\":\"1: Rossy Robinson - $25\",\"2\":\"7: Davey Ambrose - $25\",\"3\":\"14: Ross Robinson - $25\"}"];

//
// convert the json string to an NSMutableDictionary
//
NSError *e;
NSMutableDictionary *JSONdic = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];

//
// change a value and add a new value in the dict
//
NSLog(@"before: object for key 1 is: %@", [JSONdic objectForKey:@"1"]);
[JSONdic setObject:@"xxx" forKey:@"1"];
[JSONdic setObject:@"Phil McQuitty" forKey:@"2"];

//
//convert dictionary object to json data
//
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&e];

//
// convert the json data back to a string
//
NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\

//
// print out the final results
//
NSLog(@"back to string: %@", jsonText);
于 2012-08-22T10:37:15.853 回答