我有一个JSON字符串(来自PHP的json_encode()
看起来像这样:
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
我想将其解析为我的iPhone应用程序的某种数据结构。我想对我来说最好的事情就是拥有一个字典数组,所以数组中的第0个元素是一个带有键"id" => "1"
和"name" => "Aaa"
的字典。
我不明白NSJSONSerialization
如何存储数据。到目前为止,这是我的代码:
NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization
JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e];
这只是我在其他网站上看到的一个例子。我一直试图通过打印出这些元素和类似的东西来阅读JSON
对象,但我总是得到EXC_BAD_ACCESS
。
如何使用NSJSONSerialization
解析上面的JSON,并将其转换为我提到的数据结构?
答案 0 :(得分:206)
您的根json对象不是字典而是数组:
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
这可能会让您清楚地了解如何处理它:
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
答案 1 :(得分:72)
这是我检查收到的json是数组还是字典的代码:
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(@"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
NSLog(@"jsonArray - %@",jsonArray);
}
else {
NSLog(@"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(@"jsonDictionary - %@",jsonDictionary);
}
我已经尝试过这个选项:kNilOptions和NSJSONReadingMutableContainers,并且两者都能正常工作。
显然,在if-else块中创建NSArray或NSDictionary指针时,实际代码不能这样。
答案 2 :(得分:27)
它对我有用。您的data
对象可能是nil
,并且正如rckoenes所指出的,根对象应该是(可变的)数组。看到这段代码:
NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@", json);
(我不得不使用反斜杠转义JSON字符串中的引号。)
答案 3 :(得分:8)
您的代码似乎没问题,但结果是NSArray
,而不是NSDictionary
,这是一个示例:
前两行只是用JSON创建一个数据对象,就像你从网上读取它一样。
NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *jsonList = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"jsonList: %@", jsonList);
NSLog内容(词典列表):
jsonList: (
{
id = 1;
name = Aaa;
},
{
id = 2;
name = Bbb;
}
)
答案 4 :(得分:6)
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
在上面的JSON数据中,您显示我们有一个包含字典数的数组。
您需要使用此代码进行解析:
NSError *e = nil;
NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
for(int i=0;i<[JSONarray count];i++)
{
NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
}
对于swift 3/3 +
//Pass The response data & get the Array
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
print(jsonData)
// considering we are going to get array of dictionary from url
for item in jsonData {
let dictInfo = item as! [String:AnyObject]
print(dictInfo["id"])
print(dictInfo["name"])
}
答案 5 :(得分:3)
以下代码从Web服务器获取JSON对象,并将其解析为NSDictionary。我使用了openweathermap API,它为此示例返回一个简单的JSON响应。为了简单起见,此代码使用同步请求。
NSString *urlString = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
NSURL *url = [[NSURL alloc]initWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
Nslog(@"%@",res);
答案 6 :(得分:2)
@rckoenes已经向您展示了如何从JSON字符串中正确获取数据。
对于您提出的问题:EXC_BAD_ACCESS
几乎总是在您尝试访问[自动]释放后的对象时出现。这不是特定于JSON [de-]序列化,而是与您获取对象然后在它被释放后访问它有关。它通过JSON发布的事实并不重要。
有很多页面描述了如何调试这一点 - 您想要Google(或SO)obj-c zombie objects
,特别是NSZombieEnabled
,这对您来说非常有用,可帮助您确定你的僵尸对象的来源。 (“Zombie”是你释放一个对象时所调用的,但保留一个指针并稍后尝试引用它。)
答案 7 :(得分:1)
使用do / try / catch块在Xcode 7(Beta)上使用Swift 2.0:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1" id="form1">
<input type="text" name="firstname" value="ABCD"/>
<input type="text" name="lastname" value="XYZ"/>
</form>
答案 8 :(得分:1)
注意:对于Swift 3 。 您的JSON字符串返回Array而不是Dictionary。请尝试以下内容:
//Your JSON String to be parsed
let jsonString = "[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
//Converting Json String to NSData
let data = jsonString.data(using: .utf8)
do {
//Parsing data & get the Array
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
//Print the whole array object
print(jsonData)
//Get the first object of the Array
let firstPerson = jsonData[0] as! [String:Any]
//Looping the (key,value) of first object
for (key, value) in firstPerson {
//Print the (key,value)
print("\(key) - \(value) ")
}
} catch let error as NSError {
//Print the error
print(error)
}
答案 9 :(得分:0)
#import "homeViewController.h"
#import "detailViewController.h"
@interface homeViewController ()
@end
@implementation homeViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.frame = CGRectMake(0, 20, 320, 548);
self.title=@"Jason Assignment";
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self clientServerCommunication];
}
-(void)clientServerCommunication
{
NSURL *url = [NSURL URLWithString:@"http://182.72.122.106/iphonetest/getTheData.php"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
if (connection)
{
webData = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
/*Third party API
NSString *respStr = [[NSString alloc]initWithData:webData encoding:NSUTF8StringEncoding];
SBJsonParser *objSBJson = [[SBJsonParser alloc]init];
NSDictionary *responseDict = [objSBJson objectWithString:respStr]; */
resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:@"result"]];
NSLog(@"resultArray: %@",resultArray);
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [resultArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"name"];
cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"designation"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"]]];
cell.imageview.image = [UIImage imageWithData:imageData];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here, for example:
//Create the next view controller.
detailViewController *detailViewController1 = [[detailViewController alloc]initWithNibName:@"detailViewController" bundle:nil];
//detailViewController *detailViewController = [[detailViewController alloc] initWithNibName:@"detailViewController" bundle:nil];
// Pass the selected object to the new view controller.
// Push the view controller.
detailViewController1.nextDict = [[NSDictionary alloc]initWithDictionary:[resultArray objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:detailViewController1 animated:YES];
// Pass the selected object to the new view controller.
// Push the view controller.
// [self.navigationController pushViewController:detailViewController animated:YES];
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
empName.text=[nextDict valueForKey:@"name"];
deptlbl.text=[nextDict valueForKey:@"department"];
designationLbl.text=[nextDict valueForKey:@"designation"];
idLbl.text=[nextDict valueForKey:@"id"];
salaryLbl.text=[nextDict valueForKey:@"salary"];
NSString *ImageURL = [nextDict valueForKey:@"image"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
image.image = [UIImage imageWithData:imageData];
}
答案 10 :(得分:0)
问题似乎与对象的自动释放有关。 NSJSONSerialization JSONObjectWithData显然是创建一些自动释放的对象并将其传递给您。如果你试图把它带到另一个线程,它将无法工作,因为它不能在另一个线程上解除分配。
诡计可能是尝试做一个字典或数组的可变副本并使用它。
NSError *e = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e] mutableCopy];
将NSDictionary作为NSArray处理不会导致错误访问异常,但在进行方法调用时可能会崩溃。
另外,可能这里的选项并不重要但是最好给NSJSONReadingMutableContainers | NSJSONReadingMutableContainers | NSJSONReadingAllowFragments但即使它们是自动释放的对象,也可能无法解决此问题。
答案 11 :(得分:0)
不好的例子,应该是这样的 {“ id”:1,“ name”:“某物”}
数字和字符串混合在一起。