Parse JSON file using AFNetworking
Change the second line in this:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
to this:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
Note you are using the AFJSONResponseSerializer
response serialised.
Update
Updating my answer from info in the below comments, it appears you actually want to download a JSON file from a server and then parse it as opposed to parsing JSON directly from the HTTP response:
In order to do that change the content type to text/plain
and with the downloaded file/data
parse either as a String
or a JSON
object like this:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:nil];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes =
[NSSet setWithObjects:@"application/octet-stream", @"text/plain", nil];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"JSON: %@", json);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
AFNetworking and jSON
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
Update 2: https://github.com/SSamanta/SSHTTPClient (Using Swift)
Available Pod : pod 'SSHTTPClient', '~>1.2.2'
Parsing JSON with AFNetworking
You have an array of dictionaries. To have an array of outputs you can use the following method:
- (NSMutableArray *)getValueString: (NSString*)string fromArray: (NSArray *)inputArray {
NSString *outputString;
NSMutableArray *outputArray = [NSMutableArray new];
for (id dict in inputArray) {
if ([[dict class] isSubclassOfClass:[NSDictionary class]]) {
outputString = [dict valueForKey: string];
}
else {
outputString = @"Name not found";
}
if (!(outputString.length > 0)) {
outputString = @"Name not found";
}
[outputArray addObject: outputString];
}
return outputArray;
}
And use it to get name with:
NSArray *resultArray = [self getValueString: @"name" fromArray: inputArray];
NSString *firstName = resultArray[0];
And to get id with:
NSArray *resultArray = [self getValueString: @"id" fromArray: inputArray];
NSString *firstId = resultArray[0];
Parse JSON from AFNetworking - Swift
you could do something like:
let manager = AFHTTPRequestOperationManager()
manager.GET("http://api.androidhive.info/json/movies.json", parameters: nil, success: { (operation, responseObject) -> Void in
let jsonArrays = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSArray
var arrayofDesiereValue : [String] = []
for value in jsonArrays {
if let value = value as? NSDictionary {
arrayofDesieredValue.append(value["desideredkey"] as! String)
}
}
}, failure: nil)
How to parse a response obtained with AFNetworking 1.0 using JSON format
This solved my problem:
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:jailbreakRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *requestOperation, id responseObject) {
//Place this line of code below to create a NSDictionary from the async server response
NSDictionary *jsonList = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
} failure:^(AFHTTPRequestOperation *requestOperation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[requestOperation start];
Thanks anyway :-)
Related Topics
iOS Document/File Type Associations - Wildcard Uti
How to Calculate Current Location in Watchkit Extension
Simple Sprite Kit Scene Setup Going Wrong
Programmatically Added Constraint Not Working
Re-Assigning Instance of Avaudioplayer in iOS13 Leads to Bad_Access Runtime Error
Uilabel and Uitextview Line Breaks Don't Match
How to Reload Tableview of Another Uiviewcontroller in Current Viewcontroller
iOS How to Use Uiapplication Launchapplicationwithidentifier Which Is in Private APIs
Delphi/Firemonkey Change iOS Screen Rotation at Runtime
How to Encrypt Using Aes Gcm on iOS
Drawing Rounded Rect in Core Graphics
Not Working Transitions in Spritekit
Didreceiveremotenotification Function Doesn't Called with Fcm Notification Server
How to Remove the Bottom Gap of Uipageviewcontroller
Check If 3D Touch Is Supported and Enabled on the iOS9 Device
Mapkit Annotations Disappearing
iOS - Using Storyboard and Autolayout to Center the Uiscrollview