Apparently, the server can't understand my dictionary with array.
I wrote this
NSURL *url = [NSURL URLWithString:#"http://"];
self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[self.manager setResponseSerializer:responseSerializer];
self.manager.responseSerializer.acceptableContentTypes = [self.manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
[SOUser sharedManager].id, #"id",
#"vk", #"socialId",
[SOUser sharedManager].firstName, #"firstName",
[SOUser sharedManager].lastName, #"lastName",
[SOUser sharedManager].sex, #"gender",
[SOUser sharedManager].friends, #"friends", nil];
[self.manager POST:#"api/user/"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
NSLog(#"OPERATION = %#", operation);
NSLog(#"%#", operation.responseString);
NSLog(#"JSON: %#", responseObject);
NSLog(#"Token = %#", [responseObject objectForKey:#"token"]);
[SOUser sharedManager].legendaryToken = [responseObject objectForKey:#"token"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"message: %#", [operation.responseObject objectForKey:#"message"]);
NSLog(#"operation: %#", [operation.responseObject objectForKey:#"errors"]);
NSDictionary *ac = [operation.responseObject objectForKey:#"errors"];
NSLog(#"%#", [ac objectForKey:#"email"]);
NSString *fg = [ac objectForKey:#"email"];
NSLog(#"%#", fg);
}];
Where [SOUser sharedManager].friends is NSMutableArray:
for (int i = 0; i < 25; i++) {
[self.friends addObject:[NSString stringWithFormat:#"%i", i]];
}
And on server i receive all my data but instead of my array with my numbers server print string "array"? What it can be?
My JSON :
JSON: {
email = "<null>";
"fb_friends" = "<null>";
"fb_id" = "<null>";
firstName = Sergey;
gender = 2;
id = 17;
lastName = Oleynich;
phone = "<null>";
token = 6990b71a61411d9d038dad1e2a54dd9f;
"vk_friends" = (
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24
);
"vk_id" = 3;
server
JSON : Id:17
vk_id:3
fb_id:NULL
firstName:Sergey
lastName:Oleynich
gender:2
email:NULL
vk_friends:Array
I would suggest that your request might be fine, but that the problem may simply be the manner in which you are displaying the "server" values at the end of your question. For example, if your server was written in PHP and you echo the variable that holds the array of vk_friends, it would simply display "Array".
If you want to display the array in PHP, you'd do something like:
foreach ($vk_friends as $vk_friend) {
echo $vk_friend . "\r\n";
}
Frankly, if your server was responding to the app, you'd probably use json_encode, anyway, and this point is moot. But this might be why you are currently seeing "Array" in your output.
Related
I'm attempting to obtain elements extracted from a dictionary and convert them to doubles. The data is being pulled from JSON and seems to be extracted into a type of array (not sure which type). Is there a way to obtain the numbers listed below individually out of the array? Please let me know if you need more information.
NSDictionary *parameters = #{#"username":savedUser,#"password":savedPass};
NSURL *URL = [NSURL URLWithString:#"testwebsite"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:URL.absoluteString parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSError *error = nil;
JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if (error) {
NSLog(#"Error serializing %#", error);
}
NSLog(#"%#",JSON);
NSString *price = [NSString stringWithFormat:#"%#",[JSON valueForKey:#"UnitPrice"]];
price= [price stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"Price: %#",price);
[transactionTotals addObject:price];
[self createGraph:100];
}
failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error1: %#", [error debugDescription]);
NSLog(#"Error2: %#", [error localizedDescription]);
}];
}
#catch (NSException *exception)
{
NSLog(#"%#",exception);
}
Log (UnitPrice values I need individually extracted):
Dictionary output:
2016-07-03 22:52:21.330 T2PApp[2272:658440] (
{
OrderDetailID = 3;
ProductName = Oranges;
UnitPrice = "399.99";
date = "2016-06-09T21:45:06";
},
{
OrderDetailID = 7;
ProductName = Oranges;
UnitPrice = 1000;
date = "2016-06-13T22:15:47.107";
}
)
Extracted UnitPrice output (still not completely extracted):
2016-07-03 22:52:21.330 T2PApp[2272:658440] Price: (
399.99,
1000
)
I think what you need is digging out the data from the objects in array. It not about the JSON.
There is many way to do it, but not one simply way to dig it out.
For example, create a new array, and traverse the target array, put the property you need into the new array.
It is basically like that.
In your code, maybe the code below will work.
NSLog(#"%#",JSON);
NSMutableArray *priceArr = [NSMutableArray array];
NSArray *arr = nil;
if ([JSON isKindOfClass:[NSArray class]]) {
arr = (NSArray *)JSON;
for (NSDictionary *dic in arr) {
NSString *price = [NSString stringWithFormat:#"%#",[dic valueForKey:#"UnitPrice"]];
price= [price stringByReplacingOccurrencesOfString:#"\"" withString:#""];
[priceArr addObject:price];
}
}
priceArr is what you need.
As a response to a request I get JSON:
{
"letters": {
"A": 0,
"B": 1,
"C": 2,
"D": 3,
"E": 4,
...
}
}
That's my code to acquire this JSON:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle error
}];
I want to fill array with keys (not values) like this:
array[0] = "A"
array[1] = "B"
...?
NSMutableArray *parts = [NSMutableArray new];
NSDictionary *allletters = [responseObject objectForKey:#"letters"];
for (NSString *key in [allletters allKeys])
{
NSString *value = [allletters objectForKey: key];
[parts insertObject:key atIndex:[val intValue]];
}
I haven't tested the code. But it should be something similar to this:
NSDictionary *responseDictionary = (NSDictionary*)responseObject;
NSDictionary *letters = [responseDictionary objectForKey:"letters"];
NSMutableArray *lettersArray = [[NSMutableArray alloc]init];
if ( letters ){
for (NSInteger i = 0; i < letters; ++i)
{
[lettersArray addObject:[NSNull null]];
}
[letters enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id key, id object, BOOL *stop) {
[lettersArray replaceObjectAtIndex:[key integerValue] withObject:object]
}]
}
try the following code
NSDictionary *letters = [responseObject objectForKey:"letters"];
NSArray *lettersArray = [letters allKeys];
As you are already using the JSON response serializer, responseObject should be a dictionary.
To get all keys of the sub dictionary letters, do
NSArray *letters = [reponseObject[#"letters"] allKeys];
No need for a mutable array here. But if you want it mutable , do
NSMutableArray *letters = [[reponseObject[#"letters"] allKeys] mutableCopy];
- The structure that I am trying to create is
[{'category_id': '3'}, {'category_id': '2'}, {'category_id': '1'}]
- I tried creating the same using NSMutableArray of NSMutableDictionary & the structure that i got back was:
<__NSArrayM 0x7c186080>(
{
"category_id" = 1;
},
{
"category_id" = 2;
},
{
"category_id" = 3;
}
)
- I am sending this to server over HTTPPost.
- But on the server the request is reaching as:
{(null)[][category_id]': ['1', '2', '3']}
Which is not in the desired format as i showed above in point 1.
- Can anyone please help me out create an JSONArray of JSONObjects, I would be really obliged.
The code that i used to create and send the request to server is:
-(void) getProductList:(NSString *)strToken andCatId:(NSArray *)arrCategory{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:strToken forHTTPHeaderField:#"Authorization"];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
NSString *strSuffix = #"unfollow/productList/";
NSString *strUrl = [NSString stringWithFormat:#"%#%#",BASE_URL,strSuffix];
api_categoryProductList *currentObj = self;
[manager POST:strUrl parameters:arrCategory success:^(AFHTTPRequestOperation *operation, id responseObject) {
[currentObj httpOperationDidSuccess:oper
ation responseObject:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[currentObj httpOperationDidFail:operation error:error];
}];
}
Try this:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *id = [NSNumber numberWithInt:1];
for (int i = 0; i < 5; ++i) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:id forKey:#"category_id"];
[array addObject:dict];
}
Right now it has static id as 1. You can change it to whatever value you like.
i have a problem. I have to parse this json:
{
"category_id" = 1;
fullname = "Wiadomo\U015bci";
name = wiadomosci;
"page_index" = 0;
"show_live" = 1;
},
{
"category_id" = 2;
fullname = Kultura;
name = kultura;
"page_index" = 1;
"show_live" = 0;
},
{
"category_id" = 3;
fullname = Rozrywka;
name = rozrywka;
"page_index" = 2;
"show_live" = 0;
},
{
"category_id" = 4;
fullname = Biznes;
name = biznes;
"page_index" = 3;
"show_live" = 0;
}
I have two arrays with category_id, full name, name and page_index.
How to do?
I used AFnetworking:
self.manager = [AFHTTPRequestOperationManager manager];
[self.manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
[self.manager GET:#"http://webapi.test.pl/newsCategoriesForMobileApp/iphone" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
and I'don't know how to parsing json.
You already have array of dictionaries, you need to just do the following
for(NSDictionary *dic in jsonArray){
NSLog(#"%#, %#, %#",[dic objectForKey:#"category_id"],[dic objectForKey:#"fullname"],[dic objectForKey:#"page_index"]);
}
if this array named array. You can get property by
NSDictionary *dictionary = [array objectAtIndex:page_index];
NSString *fullname = [NSString stringWithFormat:#"%#", [dictionary objectForKey:#"fullname"]];
NSInteger category_id = [[dictionary objectForKey:#"category_id"] integerValue];
This is duplicate of this
In short:
Use NSJSONSerialization class
and check NSDictionary
hi i need to send a array as a one of the parameter in Afnetworking Query String
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.008.0.28/aaa/a/"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: #"20", #"Miles", [NSArray arrayWithObjects:#"1",#"2",#"3",nil], #"Interval", nil];
[httpClient postPath:iUpdateNotificationMethod parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
But server side we got "Miles":20,"Intervals":null how to fix it
Thanks,
Try This
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:OAuthBaseURL];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:0];
for (int i =0; i < [userIDs count]; i++) {
NSString *userID = [[userIDs objectAtIndex:i] objectForKey:#"id"];
NSDictionary *tmpDict = [NSDictionary dictionaryWithObjectsAndKeys:userID , [NSString stringWithFormat:#"ids[%i]",i], nil];
[parameters addEntriesFromDictionary:tmpDict];
}
[client postPath:#"/user"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *data = (NSData *)responseObject;
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"jsonStr %#",jsonStr);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self showError];
}
];
Since you're submitting an array, AFNetworking is generating a different parameter name and overloads it with the values you supply. For example, your request generates the following querystring:
Interval[]=1&Interval[]=2&Interval[]=3&Miles=20
This is defined in AFHTTPClient.m in the AFQueryStringPairsFromKeyAndValue function.
If you want to keep the original parameter, you should decide how to convert your NSArray to NSString by yourself. For example, you can do something like [myArray componentsJoinedByString:#","] and then split it back to elements on the server. If you choose this method, beware of using characters that might appear in your actual data.
I believe this will work:
params = #{ #"Miles": #"20", #"Interval": #[#"1",#"2",#"3"] };