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 に答える