I have used the below code to convert the JSON data(from SOAP service) to NSDictionary.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
}
Output
2017-04-04 13:03:51.085 SoapService[18444:588594] (
{
firstName = "1 Jhon";
lastName = Macay;
},
{
firstName = "2 William";
lastName = Proter;
},
{
firstName = "3 Joe";
lastName = Root;
},
{
firstName = "4 Brendon";
lastName = Haejoy;
},
{
firstName = "5 Jhon";
lastName = Snow;
},
{
firstName = "6 Theon";
lastName = Greyjoy;
}
)
Do I need to convert this to any other? or how could I bind the above output in UITableView?
To work with table view you need array
Checkout this simple table view tutorial
It should be like this
Declare jsonArray in your .h file
#property (strong, nonatomic) NSMutableArray *jsonArray;
Add below line viewDidLoad
self.jsonArray = [[NSMutableArray alloc]init];
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",son);
[self.jsonArray addObject:[[json objectForKey:#"firstname"]stringByAppendingString:[json objectForKey:#"lastname"]];
[tableViewName reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [self.jsonArray objectAtIndex:indexPath.row];
return cell;
}
take one NSMutuableArray and add dictionary to this array like
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: json];
//Than Reload Tableview
Note: Declare array Globally to access in your class
tableview display data like
cell.label.text = [[array objectAtIndex:indexPath.row]valueForKey:#"firstName"];
Store json data into Global Declare NSArray.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
DataArray = [NSArray arrayWithObjects:json, nil];
[tableView reloadData];
}
Here DataArray is Globally Declare NSArray Object;
Now Write UITableView DataSource Method.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return DataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"jsoncell" forIndexPath:indexPath];
NSDictionary *dict = DataArray[indexPath.row];
NSString *output = [NSString stringWithFormat:#"%# %#",dict[#"firstName"],dict[#"lastName"]];
cell.textLabel.text = output;
return cell;
}
Related
I am parsing a json to display the contents in the tableview. I have the array containing parsed json being populated in getReceivedData which is called after the UITAbleView Delegate methods. So it is problem in populating tableview as when the compiler attempts to populate it the array is not yet initialized.
- (void)getReceivedData:(NSMutableData *)data sender:(RestAPI *)sender{
NSError * error=nil;
NSArray *receivedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSString *dictionaryKey=#"department";
NSString *predicateString=#"software";
NSPredicate *predicate=[NSPredicate predicateWithFormat:#" %K == %# ", dictionaryKey,predicateString];
NSArray *shortlisted=[receivedData filteredArrayUsingPredicate:predicate];
for(int i = 0; i<shortlisted.count; i++)
{
NSDictionary *detailItems=[shortlisted objectAtIndex:i];
NSString *name=[detailItems objectForKey:#"emp_name"];
NSString *designation=[detailItems objectForKey:#"designation"];
NSString *email=[detailItems objectForKey:#"email"];
NSString *phone_no=[detailItems objectForKey:#"phone_no"];
// NSString *image=[detailItems objectForKey:#"url_path"];
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name, #"keyname",
designation, #"keydesignation",
email, #"keyid",
phone_no, #"keyphone",
nil];
[myObject1 addObject:dictionary1];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section{
if(isfiltered==YES){
return [filteredArray count];
}
else{
return [myObject1 count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyTableCell *cell=[tableView dequeueReusableCellWithIdentifier:#"myCell"];
if(!cell){
[tableView registerNib:[UINib nibWithNibName:#"MyTableCell" bundle:nil]
forCellReuseIdentifier:#"myCell"];
cell=[tableView dequeueReusableCellWithIdentifier:#"myCell"];
}
if(isfiltered==NO)
{
NSDictionary * tmpdict= [myObject objectAtIndex:indexPath.row];
cell.nameLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyname"]];
cell.designationLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keydesignation"]];
cell.idLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyid"]];
cell.phoneLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyphone"]];
cell.mainImg.image = [UIImage imageNamed:[tmpdict objectForKeyedSubscript:#"keyimage"]];
}
else{
NSDictionary * tmpdict= [filteredArray objectAtIndex:indexPath.row];
cell.nameLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyname"]];
cell.designationLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keydesignation"]];
cell.idLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyid"]];
cell.phoneLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyphone"]];
cell.mainImg.image = [UIImage imageNamed:[tmpdict objectForKeyedSubscript:#"keyimage"]];
}
return cell;
}
This window was supposed to view the table
In a mutable dictionary first you have to give object then its key. You are doing wrong
for(int i = 0; i<shortlisted.count; i++)
{
NSDictionary *detailItems=[shortlisted objectAtIndex:i];
NSString *name=[detailItems objectForKey:#"emp_name"];
NSString *designation=[detailItems objectForKey:#"designation"];
NSString *email=[detailItems objectForKey:#"email"];
NSString *phone_no=[detailItems objectForKey:#"phone_no"];
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name,#"keyname",
designation,#"keydesignation",
email,#"keyid",
phone_no,#"keyphone",
nil];
[myObject1 addObject:dictionary1];
}
Actually this is not correct way to intialize dictionary as you did, #"%#" is used %# is a placeholder in a format string for any object.
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name,#"keyname",
designation,#"keydesignation",
email,#"keyid",
phone_no,#"keyphone",
nil];
i'm trying to fill a tableview with a Json response this is the Json that i'm reading from the callback
{
"Categories": {
"Beer": [
{
"id": "3",
"nombre": "Bud ligth",
"precio": "10",
"categoriaid": "3",
"url": "false"
}
],
"Whiskey": [
{
"id": "2",
"nombre": "Red label",
"precio": "100",
"categoriaid": "2",
"url": "false"
}
]
}
}
and this is my code but it breaks the app any ideas on how can i make change my code in order to make it fill the tableview with its correspondent section and rows in each sections
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.menuInfo options:NSJSONReadingMutableContainers error:nil];
NSDictionary *cat = [json objectForKey:#"Categories"];
for(NSString *categories in cat){
Categorias *categorias = [[Categorias alloc]initWithNombre:categories];
NSDictionary *listTagDict = [cat objectForKey:categories];
for (NSString *prod in listTagDict) {
NSArray *rows = [listTagDict objectForKey:prod];
for (NSDictionary *rowDict in rows) {
NSString* pID = [rowDict objectForKey:#"id"];
NSString* pNombre = [rowDict objectForKey:#"nombre"];
NSString* pPrecio = [rowDict objectForKey:#"precio"];
NSString* pUrl = [rowDict objectForKey:#"url"];
Productos* productos = [[Productos alloc]initWithNombre:pNombre productoID:pID precio:pPrecio iconUrl:pUrl];
[categorias addRow:productos];
}
}
}
here are my two object clases the .m part
#implementation Productos
-(id)initWithNombre:(NSString *)name productoID:(NSString *)pId precio:(NSString*)prec iconUrl:(NSString*)url{
self = [super init];
if (self) {
self.nombre = name;
self.productoID = pId;
self.precio = prec;
self.iconUrl = url;
}
return self;
}
#end
#interface Categorias(){
NSMutableArray *rows;
}
#end
#implementation Categorias
-(id)initWithNombre:(NSString *)name{
self = [super init];
if (self) {
self.nombre = name;
}
return self;
}
-(void)addRow:(Productos *)row {
[rows addObject: row];
}
-(NSArray *)rowData {
return [NSArray arrayWithArray: rows];
}
#end
you are parsing the json response in wrong way,
try this,
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.menuInfo options:NSJSONReadingMutableContainers error:nil];
NSDictionary *cat = [json objectForKey:#"Categories"];
NSMutableArray *categoryArray = [NSMutableArray new];
for(NSString *key in [cat allKeys]){
Categorias *category = [[Categorias alloc]initWithNombre:key];
NSArray *listTagDict = [cat objectForKey:key];
for (NSDictionary *prod in listTagDict) {
NSString* pID = [prod objectForKey:#"id"];
NSString* pNombre = [prod objectForKey:#"nombre"];
NSString* pPrecio = [prod objectForKey:#"precio"];
NSString* pUrl = [prod objectForKey:#"url"];
Productos* productos = [[Productos alloc]initWithNombre:pNombre productoID:pID precio:pPrecio iconUrl:pUrl];
[category addRow:productos];
}
[categoryArray addObject:category];
}
use categoryArray to populate tableview.
in this, categoryArray count will be section count, and each section contains rows with rowData array of each category.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [categoryArray count];
}
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
Category *category = [categoryArray objectAtIndex:section];
return category.nombre;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
Category *category = [categoryArray objectAtIndex:section];
NSArray *rows = [category rowData];
return [rows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath]; return cell;
Category *category = [categoryArray objectAtIndex:indexPath.section];
NSArray *rows = [category rowData];
Product *product = [rows objectAtIndex:indexPath.row];
//populate cell with product
}
I have this json
{
"title": "xyz",
"category": "Monetary",
"target": "55",
"achieve": "0",
"todolist": [
{
"todoitem": "one"
},
{
"todoitem": "two"
},
{
"todoitem": "three"
}
]
}
coming from API and I want to add todolist array to
In .h file
#property (strong, nonatomic) NSMutableArray *todolist;
#property (strong, nonatomic) NSMutableArray *todolists;
#property (strong, nonatomic) NSMutableArray *listnumber;
In .m file
todolist=[[NSMutableArray alloc] initWithObjects: nil];
todolists=[[NSMutableArray alloc] initWithObjects: nil];
listnumber=[[NSMutableArray alloc] initWithObjects: nil];
In function getting json
todolists = [result valueForKey:#"todolist"];
for (int j =0; j < todolist.count; j++)
{
[todolist addObject:[[todolists objectAtIndex:j] valueForKey:#"todoitem"]];
[listnumber addObject:[NSString stringWithFormat:#"%d", j]];
}
[tvToDoList reloadData];
CellForRowAtIndexPath I am adding values two field
static NSString *CellIdentifier=#"Cell";
TodolistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(cell==nil)
{
cell = [[TodolistTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier ];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
int row = (int)[indexPath row];
cell.valListitem.text = todolist[row];
cell.lblNo.text = listnumber[row];
return cell;
}
where result is containing the whole json
Try this in one line code.
todolist = [[[result valueForKey:#"todolist"] valueForKey:#"todoitem"] mutableCopy];
If you want to get string from array here is solution
for (int i =0; i < listnumber.count; i++)
{
[todolist addObject:[[listnumber objectAtIndex:i] valueForKey:#"todoitem"]];
}
Parse your json string and get the todos as NSArray from that.
#Try this
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&error];
NSArray *todos = [object valueForKey:#"todolist"];
NSMutableArray *mutableToDos = [[NSMutableArray alloc] initWithArray:todos];
Here is the code for display in cell
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *todo = [mutableToDos objectAtIndex:indexPath.row];
[[cell textLabel] setText:[todo valueForKey:#"todoitem"];
return cell;
}
Try this
#property (strong, nonatomic) NSMutableArray *todolist;
todolist=[[NSMutableArray alloc] initWithObjects: nil];
//Convert to NSData
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//JSON object
id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//Array of ToDo List
NSArray *list = (NSArray *)[object valueForKey:#"todolist"];
//Fetch items of ToDo List
for (int i =0; i < [list count]; i++)
{
[todolist addObject:[[list objectAtIndex:i] valueForKey:#"todoitem"]];
}
NSLog(#"Array :: %#", todolist);
Hopefully, this will help you.
Thanks.
I need to display the address in a tableview. How can i break the JSON and save the addresses in an NSArray.
The JSON is :
{
"Rank": 54,
"data": [
{
"number": 1,
"address": "x mandt "
},
{
"number": 2,
"address": "x mandt2 "
}
]
}
COde is:
NSDictionary *dic = (NSDictionary *) responseObject;
NSDictionary * dat = [dic objectForKey:#"data"];
NSArray *add =[dat objectForKey:#"address"];
The above code, doesn't retrieve and save all the address in the add array. How can i solve this?
assume that this is your serialization data
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
// here I start your work
NSArray *infoDict=[jsonArray objectForKey:#"data"];
for (NSDictionary *tmp in infoDict)
{
NSMutableDictionary *temparr=[[NSMutableDictionary alloc]init];
[temparr setValue:[tmp objectForKey:#"number"] forKey:#"number"];
[temparr setValue:[tmp objectForKey:#"address"] forKey:#"address"];
[_tdataSource addObject:temparr];
}
[yourtableviewNAme reloadData];
here I add the Tableview DataSource and delegate method
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [self.tdataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"resultCell";
yourtableviewCellName *cell = [self.yourtableName dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[yourtableviewCellName alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text=[[self.tdataSource objectAtIndex:indexPath.row]objectForKey:#"address"];
return cell;
}
I think you better just use the literal syntax for retrieving this. The way you retrieve is just fine. You probably just add some introspection:
NSDictionary *responseDict = (NSDictionary *) responseObject;
if (responseDict.count) {
NSArray *dataArray = responseDict[#"data"];
if (dataArray.count) {
// do whatever you want
}
}
You made a mistake when you retrieve the key word data, you will get an array after that but not a NSDictionary.
It should be:
NSArray *add =[dic objectForKey:#"data"];
Then if you want to have the address (I am considering address in 0'th index) then do this:
NSString *str = [[add objectAtIndex: 0] objectForKey:#"address"];
Edit:
Declare a class variable like:
#interface YourClassName (){
NSMutableArray *dataSource;
}
Populate the dataSource like:
dataSource =[dic objectForKey:#"data"];
Then In your cellForRowAtIndexPath method do this:
cell.textLabel.text = [[dataSource objectAtIndex:indexPath.row] objectForKey:#"address"];
I am considering you have single section in your tableview. Hope this helps.. :)
I am calling some JSON and loading a table with the data from a single array. That's working great. Now I'm trying to figure out
A. the best way to load the data into the table and
B. the best way to section that data off.
This is my 6th week of iOS development and I am pretty new. I have a fairly weak Javascript background.
My first (failed attempt) way to concatenate the arrays together and pass that to the tableview. I think this is wrong for multiple reasons (issues with sectioning afterwards, know "which" one to delete, etc). Any help is greatly appreciated!
Didn't work:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&errorJson];
self.allGroups = [dataDictionary objectForKey:#"all_groups"]; //NSDictionary
self.firstGroup = [self.allGroups objectForKey:#"first_group"]; //NSMutableArray
self.secondGroup = [self.allGroups objectForKey:#"second_group"]; //NSMutableArray
self.thirdGroup = [self.allGroups objectForKey:#"third_group"]; //NSMutableArray
NSMutableArray *allGroupsArray = [self.firstGroup arrayByAddingObjectsInArray:[self.secondGroup arrayByAddingObjectsInArray:self.thirdGroup]];
Does work now, but can't figure out multiple arrays into the tableview:
-(void) getTheData {
NSString *sessionToken = [[AFOAuthCredential retrieveCredentialWithIdentifier:#"myToken"] accessToken];
if (sessionToken == nil) {
LoginViewController *loginView = [[LoginViewController alloc] init];
[self presentViewController:loginView animated:NO completion:nil];
return;
}
NSURL *url = [NSURL URLWithString:#"https://greatwebsitetogetdata.com"];
AFOAuth2Client *oauthClient = [AFOAuth2Client clientWithBaseURL:url clientID:#"MY_CLIENT" secret:#"1234567890abc"];
[oauthClient getPath:#"/api/v1/json" parameters:#{#"access_token": sessionToken} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *errorJson = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&errorJson];
self.allGroups = [dataDictionary objectForKey:#"all_groups"]; //This is a NSDictionary
self.firstGroup = [self.allGroups objectForKey:#"first_group"]; //This is a NSMutableArray
self.secondGroup = [self.allGroups objectForKey:#"second_group"]; //This is a NSMutableArray
self.thirdGroup = [self.allGroups objectForKey:#"third_group"]; //This is a NSMutableArray
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.firstGroup.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *groupInfo = self.firstGroup[indexPath.row];
static NSString *cellIdentifier = #"Cell";
groupTableViewCell *cell = (groupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[groupTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.groupTitle.text= groupInfo[#"title"];
cell.groupLikes.text= [NSString stringWithFormat:#"%#", groupInfo[#"likes"]];
cell.groupRunDates.text= [NSString stringWithFormat:#"%# - %#", groupInfo[#"start_date"], groupInfo[#"end_date"]];
cell.groupAcceptance.text= groupInfo[#"acceptance_type"];
return cell;
}
I think an array of arrays would work better for you, where each array represents a section. allGroups should then contain 3 arrays.
Then you need to override the datasource method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.allGroups.count;
}
and then in:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.allGroups[section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *group = self.allGroups[indexPath.section];
NSDictionary *groupInfo = group[indexPath.row];
static NSString *cellIdentifier = #"Cell";
groupTableViewCell *cell = (groupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[groupTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.groupTitle.text= groupInfo[#"title"];
cell.groupLikes.text= [NSString stringWithFormat:#"%#", groupInfo[#"likes"]];
cell.groupRunDates.text= [NSString stringWithFormat:#"%# - %#", groupInfo[#"start_date"], groupInfo[#"end_date"]];
cell.groupAcceptance.text= groupInfo[#"acceptance_type"];
return cell;
}