Cus*_*ase 5 iphone json ios nsjsonserialization xcode4.3
我试图了解NSJSONSerialization类参考.由于缺少developer.apple.com网站上的代码示例,我输了.网上有数以百万计的例子和其他json库,但是我还没有能够使用最新版本的xcode.(我正在运行:版本4.3.1(4E1019)并在iPhone 5.0.1上进行测试)
我想使用按钮将json文件中的数据提取到我的iphone中.
让我说我从URL获取我的数据: http://companyurl/jsonfile.json(标准JSON格式)
jsonfile.json看起来像这样......;
{
"companylist":
[
{
"company":"Companyname 1",
"telephone":"1234567890",
"url":"http:\/\/www.companyname1.com\/",
"category":"category 1",
"position":"1",
},
{
"company":"Companyname 2",
"telephone":"2345678901",
"url":"http:\/\/www.companyname2.com\/",
"category":"category 2",
"position":"2",
},
{
"company":"Companyname 3",
"telephone":"3456789012",
"url":"http:\/\/www.companyname3.com\/",
"category":"category 3",
"position":"3",
}
]
}
Run Code Online (Sandbox Code Playgroud)
我在.h和我的.m文件中写什么?
谢谢你的帮助!:)
ilh*_*ctn 15
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://your_web_server/your_file...."]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
NSLog(@"Your JSON Object: %@ Or Error is: %@", response, error);
Run Code Online (Sandbox Code Playgroud)
注意:此代码适用于Xcode 4.2,在模拟器上使用iOS 5.01,在iPad设备上使用5.1
多谢你们.我想到了.(......这就是我做的:)
在我的.m文件中,我添加了以下代码:
- (IBAction)getDataFromJson:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://yourwebsite.com/jsonfile.json"];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if(jsonData != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil)
NSLog(@"%@", result);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的.h文件中,我添加了以下代码:
@interface ViewController : UIViewController
- (IBAction)getDataFromJson:(id)sender;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35707 次 |
| 最近记录: |