ios AFNetworking 和 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13473811/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:14:53  来源:igfitidea点击:

AFNetworking and jSON

iosjsonafnetworking

提问by fizampou

I am getting following the json response from a web-service api. I want to extract product data from the json. I also want to implement this using AFNetworking.

我正在关注来自网络服务 api 的 json 响应。我想从 json 中提取产品数据。我也想使用 AFNetworking 来实现这一点。

 {"products": [
    {
      "product_id": "1170",
      "name": "zzzz?",
      "sort_order": 0,
      "brand": "zzzas",
      "product_category_id": "1090",
      "location_ids": [
        "1078"
      ],
      "icon_url": "http://zzzzz.com/media/2502/zzzz.png",
      "icon_date": "Wed, 07 Nov 2012 14:03:47 GMT",
      "thumbnail_url": "http://zzzz.com/media/2591/zzdfs.png",
      "thumbnail_date": "Wed, 07 Nov 2012 14:04:02 GMT"
    },
    {
      "product_id": "1126",
      "name": "ddddd?",
      "sort_order": 1,
      "brand": "dddsas",
      "product_category_id": "1110",
      "location_ids": [
        "1095"
      ],
      "icon_url": "http://zzzzz.com/media/2507/ddddd.png",
      "icon_date": "Wed, 07 Nov 2012 14:03:48 GMT",
      "thumbnail_url": "http://zzzzz.com/media/2596/sssds.png",
      "thumbnail_date": "Wed, 07 Nov 2012 14:04:05 GMT"
    }
]}

Can anyone suggest a way to do this.me how the things will be done.

任何人都可以建议一种方法来做到这一点,.我将如何完成这些事情。

回答by Susim Samanta

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"link"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSDictionary *jsonDict = (NSDictionary *) JSON;
        NSArray *products = [jsonDict objectForKey:@"products"];
        [products enumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop){
            NSString *productIconUrl = [obj objectForKey:@"icon_url"];
        }];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
        NSError *error, id JSON) {
            NSLog(@"Request Failure Because %@",[error userInfo]); 
    }
];

[operation start];

Try this.

尝试这个。

Update 1: You can try this https://github.com/SSamanta/SSRestClient

更新 1:你可以试试这个https://github.com/SSamanta/SSRestClient

Update 2: https://github.com/SSamanta/SSHTTPClient(Using Swift)

更新 2:https: //github.com/SSamanta/SSHTTPClient(使用 Swift)

Available Pod :pod 'SSHTTPClient', '~>1.2.2'

可用豆荚:pod 'SSHTTPClient', '~>1.2.2'

回答by raed

if you're using AFNetworking 3.0, AFJSONRequestOperationdoesn't exist anymore, you have to use AFHTTPSessionManager:

如果您使用的 AFNetworking 3.0AFJSONRequestOperation不再存在,则必须使用AFHTTPSessionManager

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

回答by Michael Mior

To parse JSON with AFNetworking, just create a subclass and add the following during initialization.

要使用 AFNetworking 解析 JSON,只需创建一个子类并在初始化期间添加以下内容。

[self registerHTTPOperationClass:[AFJSONRequestOperation class]];

Then calling a method like GET:parameters:completion:will call the completion block with an NSDictionaryas the responseparameter (assuming the JSON is valid).

然后调用一个像这样的方法GET:parameters:completion:将调用一个NSDictionary作为response参数的完成块(假设 JSON 是有效的)。

To download the images, assuming you want to display them, check out UIImageView+AFNetworking.

要下载图像,假设您想显示它们,请查看UIImageView+AFNetworking

回答by tilo

If you are just starting, I'd recommend using RestKitfor this task (it makes use of AFNetworking). See an example here.

如果您刚刚开始,我建议您使用RestKit来完成此任务(它使用 AFNetworking)。请参阅此处的示例。

回答by Wang Yandong

Please check the example of AFNetworking https://github.com/AFNetworking/AFNetworking/tree/master/Example

请检查 AFNetworking https://github.com/AFNetworking/AFNetworking/tree/master/Example的示例

For image downloading, EGOCache & EGOImageLoading may be a good choice https://github.com/enormego/EGOImageLoading

对于图片下载,EGOCache & EGOImageLoading 可能是一个不错的选择 https://github.com/enormego/EGOImageLoading

回答by kernix

Use JSONModelto parse json into object.

使用JSONModel将 json 解析为对象。

回答by Placeholder

First, in order to run AFNetworking you will first need to install “CocoaPods“. What is this? CocoaPods is a dependency manager for for Objective-C which makes installing third party libraries as AFNetworking much more faster and secure. It is provided as a Ruby Gem which you can install the following way:

首先,为了运行 AFNetworking,您首先需要安装“CocoaPods”。这是什么?CocoaPods 是 Objective-C 的依赖管理器,它使得将第三方库安装为 AFNetworking 更加快速和安全。它作为 Ruby Gem 提供,您可以通过以下方式安装:

Open up the terminal and execute the following commands:

打开终端并执行以下命令:

sudo gem install cocoapods -V

Be patient. This command can take some time to finish, so the “-V” option will provide you with detailed data what's going on.

要有耐心。此命令可能需要一些时间才能完成,因此“-V”选项将为您提供正在发生的详细数据。

Next we execute:

接下来我们执行:

pod setup

Which sets up our CocoaPods installation.

它设置了我们的 CocoaPods 安装。

Now we have to create a PodFile which will server as our config file for CocoaPods.

现在我们必须创建一个 PodFile,它将作为 CocoaPods 的配置文件。

Back to the terminal and we write the following commands:

回到终端,我们编写以下命令:

touch Podfile
open -e Podfile

The first command will create a file named “Podfile” with the Unix touch editor. The second line will open this newly created file for editing. By now, you should see an empty TextEdit window opened. Now we paste the following inside this file:

第一个命令将使用 Unix 触摸编辑器创建一个名为“Podfile”的文件。第二行将打开这个新创建的文件进行编辑。现在,您应该看到一个空的 TextEdit 窗口已打开。现在我们将以下内容粘贴到此文件中:

platform :ios, '7.0'
pod "AFNetworking", "~> 2.0"

Now it is time to set up our Cocoa working environment. IMPORTANT: Please make sure to change your directory with your terminal at your XCODE PROJECT'S CURRENT DIRECTORY by using the ‘cd' command in the terminal. Example:

现在是时候设置我们的 Cocoa 工作环境了。重要提示:请确保使用终端中的“cd”命令在 XCODE 项目的当前目录中使用终端更改目录。例子:

cd /user/xcode/myproject

Once you are sure that you are at the proper directory execute the following terminal command:

一旦确定您位于正确的目录中,请执行以下终端命令:

pod setup

And then we install the dependencies to our project by writing:

然后我们通过编写将依赖项安装到我们的项目中:

pod install

Now, this is an important note: Since you are trying to install a project which was previously not inside your current Xcode project you have to create a Workspace for your current Xcode project (if you have not done this already.) To create a workspace for your Xcode project do the following:

现在,这是一个重要的注意事项:由于您正在尝试安装一个以前不在当前 Xcode 项目中的项目,因此您必须为当前的 Xcode 项目创建一个工作区(如果您还没有这样做)。要创建一个工作区对于您的 Xcode 项目,请执行以下操作:

File > Save Workspace

Once you are done, navigate to the directory of your Xcode workspace file and execute the following command:

完成后,导航到 Xcode 工作区文件的目录并执行以下命令:

open YourProjectName.xcworkspace

Now you can just use “import ” at the beginning of any of your files to access the builtin API functionalities of AFNetworking.

现在,您只需在任何文件的开头使用“import”即可访问 AFNetworking 的内置 API 功能。