It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我正在像这样得到NSString

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


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

最佳答案

您需要使用以下代码。

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

10-07 12:26