在 iOS 中使用 NSJSONSerialization 进行 JSON 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20399087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON parsing using NSJSONSerialization in iOS
提问by Nayan
I am parsing a JSON
in my code. But I am getting some unexpected issues while retrieving data of parsed JSON
. So let me explain my problem.
我正在JSON
我的代码中解析 a 。但是我在检索 parsed 的数据时遇到了一些意想不到的问题JSON
。所以让我解释一下我的问题。
I have to parse following JSON
data using xcode. This is what data to be parsed looks like while I hit same URL in browser:
我必须JSON
使用 xcode解析以下数据。这是我在浏览器中点击相同 URL 时要解析的数据的样子:
{
"RESPONSE":[
{"id":"20",
"username":"john",
"email":"[email protected]",
"phone":"1234567890",
"location":"31.000,71.000"}],
"STATUS":"OK",
"MESSAGE":"Here will be message"
}
My code to reach up to this JSON
data is as follow:
我达到此JSON
数据的代码如下:
NSData *data = [NSData dataWithContentsOfURL:finalurl];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
If I print object json
using NSLog
, i.e. NSLog(@"json: %@", [json description]);
it looks like:
如果我json
使用打印对象NSLog
,即NSLog(@"json: %@", [json description]);
它看起来像:
json: {
MESSAGE = "Here will be message";
RESPONSE =(
{
email = "[email protected]";
id = 20;
location = "31.000,71.000";
phone = 1234567890;
username = john;
}
);
STATUS = OK;
}
So, here I observed two things:
所以,在这里我观察到两件事:
Sequence of keys (or nodes) (
MESSAGE
,RESPONSE
andSTATUS
) is changed as compared to web response above.The
RESPONSE
is get enclosed in'(' & ')'
braces.
与上面的 Web 响应相比,键(或节点)(
MESSAGE
,RESPONSE
和STATUS
)的序列发生了变化。该
RESPONSE
是得到括在'(' & ')'
括号内。
Now if I separate out values for keys MESSAGE
& STATUS
and NsLog
them, then they get printed as proper string.
现在,如果我将键MESSAGE
&STATUS
和NsLog
它们的值分开,那么它们将被打印为正确的字符串。
Like msgStr:Here will be message
& Status:OK
喜欢msgStr:Here will be message
& Status:OK
Butif I separate out value for RESPONSE
as a dictionary and again separating sub values of that dictionary like email
and username
, then I can't getting those as string.
但是,如果我将 forRESPONSE
作为字典的值分离出来,并再次分离该字典的子值,例如email
and username
,那么我无法将它们作为 string。
Here is the code so far I wrote:
这是到目前为止我写的代码:
NSMutableDictionary *response = [json valueForKey:@"RESPONSE"];
NSString *username = [response valueForKey:@"username"];
NSString *emailId = [response valueForKey:@"email"];
If I print username
and emailId
, then they are not getting printed as normal string, instead it outputs as:
如果我打印username
and emailId
,那么它们不会被打印为普通的 string,而是输出为:
username:(
john
)
email:(
[email protected]
)
So my question is why it's not getting as a normal string? If I tried to use this variables further then they show value enclosed within '(' & ')'
braces. Is this happening because of NSJSONSerialization
?
所以我的问题是为什么它不是普通字符串?如果我尝试进一步使用此变量,则它们会显示括在'(' & ')'
大括号内的值。这是因为NSJSONSerialization
?
回答by Suryakant Sharma
First of all in your JSON
response dictionary
, under the key 'RESPONSE' you have a array not a dictionary
and that array contains dictionary
object.
So to extract usernameand email IDso as below
首先,在您的JSON
响应中dictionary
,在键 ' RESPONSE' 下,您有一个数组而不是 adictionary
并且该数组包含dictionary
对象。所以要提取用户名和电子邮件ID,如下所示
NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy];
NSString *username = [response valueForKey:@"username"];
NSString *emailId = [response valueForKey:@"email"];
回答by Chris
When you see braces like that, it represents an array, not a dictionary. Your JSON also shows that by enclosing the data in brackets ('[' and ']'). So:
当你看到这样的大括号时,它代表一个数组,而不是一个字典。您的 JSON 还通过将数据括在方括号(“[”和“]”)中来显示这一点。所以:
RESPONSE =(
{
email = "[email protected]";
id = 20;
location = "31.000,71.000";
phone = 1234567890;
username = john;
}
);
RESPONSE is an Array of Dictionaries. To access the data, iterate through the array:
RESPONSE 是一个字典数组。要访问数据,请遍历数组:
for (NSDictionary *responseDictionary in [JSONDictionary objectForKey:@"RESPONSE"]) {
NSString *name = [responseDictionary objectForKey:@"username"];
.....
}
or grab a dictionary at an index:
或在索引处获取字典:
NSDictionary *responseDictionary = [[JSONDictionary objectForKey:@"RESPONSE"] objectAtIndex:0];
NSString *name = [responseDictionary objectForKey:@"username"];
Whenever in doubt, log the the class:
如有疑问,请记录课程:
NSLog(@"%@", [[dictionary objectForKey:@"key"] class]);
to see what is being returned from the dictionary.
查看从字典中返回的内容。
回答by Anoop Vaidya
1)Sequence of keys (or nodes) (MESSAGE, RESPONSE and STATUS) is changed as compared to web response above.
1) 与上述 Web 响应相比,键(或节点)(MESSAGE、RESPONSE 和 STATUS)的顺序发生了变化。
The NSLog
of NSDictionary
is based on the sorted keys.
该NSLog
的NSDictionary
是基于排序键。
2)The RESPONSE is get enclosed in '(' & ')' braces.
2) RESPONSE 被括在 '(' & ')' 大括号中。
RESPONSE =(
{
email = "[email protected]";
id = 20;
location = "31.000,71.000";
phone = 1234567890;
username = john;
}
);
The RESPONSE
is a key and the value is an NSArray
. The array contains one NSDictionary
object with keys as email, id, location, phone and username.
该RESPONSE
是一个键和值是NSArray
。该数组包含一个NSDictionary
对象,其键为电子邮件、ID、位置、电话和用户名。
NOTE:() says array. {} says dictionary.
注意:() 表示数组。{} 表示字典。
回答by Midhun MP
RESPONSE
contains an array not an object.
RESPONSE
包含一个数组而不是一个对象。
So try like this:
所以试试这样:
NSMutableArray *response = [json valueForKey:@"RESPONSE"];
NSString *username = [[response objectAtIndex:0] valueForKey:@"username"];
NSString *emailId = [[response objectAtIndex:0] valueForKey:@"email"];
NSLog(@"User=>[%@] Pwd=>[%@]",username ,emailId );
回答by Mithun R
pragma mark - Checking Reachability and Parsing Datas
pragma mark - 检查可达性和解析数据
NSString *urlString = [NSString stringWithFormat: @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaSyD7c1IID7zDCdcfpC69fC7CUqLjz50mcls"];
NSURL *url = [NSURL URLWithString: urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
array = [[NSMutableArray alloc]init];
array = [[jsonData objectForKey:@"results"] mutableCopy];
[jsonTableview reloadData];}
pragma mark- UITableView Delegate
pragma mark- UITableView 委托
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellid = @"cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell = [[UITableViewCell
alloc]initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellid];
cell.textLabel.text = [[array
valueForKeyPath:@"name"]objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [[array
valueForKeyPath:@"vicinity"]objectAtIndex:indexPath.row];
NSURL *imgUrl = [NSURL URLWithString:[[array
valueForKey:@"icon"]objectAtIndex:indexPath.row]];
NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
cell.imageView.layer.cornerRadius =
cell.imageView.frame.size.width/2;
cell.imageView.layer.masksToBounds = YES;
cell.imageView.image = [UIImage imageWithData:imgData];
return cell;
}
#import.h
#import.h
@interface JsonViewController :
UIViewController<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *jsonTableview;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *barButton;
@property (strong,nonatomic)NSArray *array;
@property NSInteger select;
回答by Shob-Z
By serializing the data, u get a json object. Json object and dictionary are different a bit.
通过序列化数据,你得到一个 json 对象。Json 对象和字典有点不同。
Instead of using:
而不是使用:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
use:
用:
NSDictionary *json = (NSDictionary*) data;