How multiple json parsing in ios? - ios

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

Related

Objective C Accessing Elements

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.

iOS: How do I get a list of names out of an array of dictionaries?

Im currently trying to read out Object from file from server:
NSURLSession *session = [NSURLSession sharedSession];
NSString *string = #"http://myfile.php";
//NSLog(string); //CHECK
[[session dataTaskWithURL:[NSURL URLWithString:string]
completionHandler : ^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (data.length > 0 && error == nil) {
NSError *jsonvar;
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonvar];
NSLog(#"%#", greeting);
dispatch_sync(dispatch_get_main_queue(), ^{
NSDictionary *main = [greeting objectForKey:#"array"];
//self.beaconMajor.text = [NSString stringWithFormat:#"%#", [main objectForKey:#"name"]];
});
}
}] resume];
}
This is the response i get when i do a NSLog:
array = (
{
endDate = "0000-00-00";
id = 3;
name = ruben;
startDate = "0000-00-00";
},
{
endDate = "0000-00-00";
id = 4;
name = "hallo mama";
startDate = "0000-00-00";
},
{
endDate = "0000-00-00";
id = 5;
name = heyoo;
startDate = "0000-00-00";
},
{
endDate = "0000-00-00";
id = 6;
name = "Gerard Depardieu";
startDate = "0000-00-00";
}
);
Can anyone help me out how to read out for example the "names" of this Array ?
Thanks!
You can do it manually:
NSArray *main = [greeting objectForKey:#"array"];
for (NSDictionary *dict in main) {
NSLog(#"name=%#", dict[#"name"]);
}
or you can use KVC to get all the names from the dictionaries within the array:
NSArray *main = [greeting objectForKey:#"array"];
NSArray *names = [main valueForKey:#"name"];
(When you use valueForKey on an array, it will call valueForKey on each contained object).

Fetch json data UIViewController

I'm trying to fetch json data from UIViewcontroller in objective-c.But it's not change anything in view.
what should I do ?
- (void)api {
NSLog(#"test");
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"musteri_detay",#"id": self.customerId,#"where":#""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel1"];
customer.grubu = [customersDictionary objectForKey:#"grubu"];
customer.adres = [customersDictionary objectForKey:#"adres"];
NSNumber *customerType = [customersDictionary objectForKey:#"kayit_tipi"];
/*
if (customerType == 1) {
customer.kayitTipi_string = #"Müşteri";
} else if (customerType == 2) {
customer.kayitTipi_string = #"Kişi";
} else if (customerType == 10) {
customer.kayitTipi_string = #"Bayi";
} else if (customerType == 20) {
customer.kayitTipi_string = #"Aday";
} else {
customer.kayitTipi_string = #"";
}
*/
[self.customerCards addObject:customer];
}
NSLog(#"Get data %#",dataDictionary);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
This is getDetails.
-(void) getDetails {
ApiClass *customers = [self.customerCards objectEnumerator];
//self.kayitTipi.text = customers.kayitTipi_string;
self.Adi.text = customers.adi;
self.faliyetAlani.text = customers.grubu;
}
And This is my viewDidLoad method.
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"ID: %#",self.customerId);
[self api];
[self getDetails];
// Do any additional setup after loading the view.
}
When I start the debuging its going api method.And [manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
after this line its going the end of method.Then going to viewdidload again.And going to getdetails method.After turn back the api method.And fetching data.But its not changing anything.

Create JSONArray of JSONObjects using AFNetworking 2.0 in Objective-C

- 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.

Can't post dictionary with array with AFNetworking

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.

Resources