NSDictionary 转 json:
- (NSString *)convertToJsonData:(NSDictionary *)dict
{
NSData*jsonData = [NSJSONSerializationdataWithJSONObject:dictoptions:0 error:nil];
if(!jsonData) returnnil;
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
输出结果:{"key1":"value1",key2:"value2"}
- (NSString *)convertToJsonData2:(NSDictionary *)dict
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
if (!jsonData) return nil;
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
输出结果:
{
"key1":"value1",
key2:"value2"
}
json 转 NSDictionary:
- (NSDictionary *)dictionaryToJsonString:(NSString *)jsonString
{
if(!jsonString) return nil;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
return [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
}
输出结果:{\"key1\":\"value1\",key2:\"value2\"}