/**
* 数组转JSON.
*/
- (void)testJsonAndArray
{
NSArray *arr = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f", nil];
NSLog(@"arrar = %@",arr);
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:&error];
if (!error)
{
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json = %@",json);
}
}
/**
* 测试json和对象、字典转json
*/
- (void)testJsonAndDict
{
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"张三",@"name",
@"20",@"age",@"180",@"height", nil];
NSLog(@"DIC = %@",dict);
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error == nil)
{
NSLog(@"字典转JSON成功,JSON = %@",json);
}
}
/**
* 把JSON转换成object对象,可能是字典、可能是数组。
*
* @param json 传进来的 json 字符串
*/
- (void)JsonToObjectWithJosn:(NSString *)json
{
// JSON 用来在网络上进行数据传输的一种数据格式。是一种特殊的字符串。
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
if (error == nil)
{
NSLog(@"%@ -- %@",result,[result class]);
}
}