我JSON
在我的代码中解析一个.但是在检索解析数据时我遇到了一些意想不到的问题JSON
.那么让我解释一下我的问题.
我必须JSON
使用xcode 解析以下数据.当我在浏览器中点击相同的URL时,这就是要解析的数据:
{ "RESPONSE":[ {"id":"20", "username":"john", "email":"abc@gmail.com", "phone":"1234567890", "location":"31.000,71.000"}], "STATUS":"OK", "MESSAGE":"Here will be message" }
我达到此JSON
数据的代码如下:
NSData *data = [NSData dataWithContentsOfURL:finalurl]; NSError *error; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
如果我json
使用打印对象NSLog
,即NSLog(@"json: %@", [json description]);
它看起来像:
json: { MESSAGE = "Here will be message"; RESPONSE =( { email = "abc@gmail.com"; id = 20; location = "31.000,71.000"; phone = 1234567890; username = john; } ); STATUS = OK; }
所以,在这里我发现了两件事:
键(或节点)的序列(MESSAGE
,RESPONSE
和STATUS
)被改变相比上述网络响应为.
该RESPONSE
是得到括在'(' & ')'
括号内.
现在,如果我将键MESSAGE
和/ STATUS
和NsLog
它们的值分开,那么它们将被打印为正确的字符串.
喜欢msgStr:Here will be message
& Status:OK
但是,如果我将值RESPONSE
作为字典分离并再次将该字典的子值分隔为email
和username
,那么我就不能将它们作为字符串.
这是我写的代码到目前为止:
NSMutableDictionary *response = [json valueForKey:@"RESPONSE"]; NSString *username = [response valueForKey:@"username"]; NSString *emailId = [response valueForKey:@"email"];
如果我打印username
和emailId
,那么他们都没有得到打印为正常的字符串,而是作为输出:
username:( john ) email:( abc@gmail.com )
所以我的问题是为什么它不是正常的字符串?如果我尝试进一步使用这些变量,那么它们会在'(' & ')'
括号内显示值.这是因为发生了NSJSONSerialization
吗?
首先,在您的JSON
响应中dictionary
,在" RESPONSE " 键下,您有一个数组而不是a dictionary
,该数组包含dictionary
对象.所以要提取用户名和电子邮件ID,如下所示
NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy]; NSString *username = [response valueForKey:@"username"]; NSString *emailId = [response valueForKey:@"email"];