JSon returning Integer values into array - ios

I have successfully realized the interaction with json and returning successfully all the required entities. But i have one field that will be returned as an integer. I want to do the simplest thing and access an element of the array , which is an integer , and compare it with another integer. No matter what i do it doesn't work out : this is my code so far :
NSString *strURL2 = [NSString stringWithFormat:#"MyURL"];
NSData *dataURL2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL2]];
NSString *strResult2 = [[NSString alloc] initWithData:dataURL2 encoding:NSUTF8StringEncoding];
NSDictionary *json2 = [strResult2 JSONValue];
userExists = [json2 valueForKeyPath:#"userId"];
Where userExists is an array, and the values stored in it are NOT strings , they are Int.
Any help?!

NSString *strURL2 = [NSString stringWithFormat:#"MyURL"];
NSData *dataURL2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL2]];
NSString *strResult2 = [[NSString alloc] initWithData:dataURL2 encoding:NSUTF8StringEncoding];
NSDictionary *json2 = [strResult2 JSONValue];
Now if you want to add the integer to the array (has to be NSMutableArray of course) userExists, you do it like so:
[userExists addObject:[[json2 objectForKey:#"userId"] integerValue]]
If your intention was to compare the returned integer with an integer in the array at index i then you do it like so:
if([userExists objectAtIndex:i] == [[json2 objectForKey:#"userId"] integerValue]) {
....
}

Related

Save json object in sqlite like text and retransform to dictionary on read

I want to save a Json Object in a field (text) sqlite and then read it again with a select and retransform to NSDictionary or NSMutableArray to parse the key/values
This is how i save actually in the sqlite DB
As you see, is a song object from the iTunes api. I want to read that object and parse it.
This is how i make the select query and save it in a NSDictionary while i filling and NSMutableArary
globals.arrayMyPlaylists = [[NSMutableArray alloc] init];
// Form the query.
NSString *query = #"select * from myplaylists";
// Get the results.
NSArray *listas = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
for (int i = 0; i < listas.count; i++) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSLog(#"lista %d %# %#", i, listas[i][0], listas[i][1]);
[dictionary setObject:listas[i][0] forKey:#"id"];
[dictionary setObject:listas[i][1] forKey:#"nombre"];
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
[dictionary setObject:canciones forKey:#"canciones"];
[globals.arrayMyPlaylists addObject:dictionary];
dictionary = nil;
}
When i try to read it in the cellForRowAtIndexPath method
NSArray *canciones = [[NSArray alloc] initWithArray:[[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"canciones"]];
and try to get the value for the key artworkUrl100
[cell.tapa1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", [[canciones objectAtIndex:i] valueForKey:#"artworkUrl100"]]] placeholderImage:nil];
i get the error
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7ff575810600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key artworkUrl100.'
i understand i'm messing up in some way with dictionarys/nsmutablearrays. I need some help. Thanks!
EDIT: this is how i save the data in the DB
NSString *query = [NSString stringWithFormat:#"insert into canciones (idplaylist, cancion) values ('%#', '%#')", [[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"id"], self.elementoSeleccionado];
[self.dbManager executeQuery:query];
self.elementoSeleccionado is the NSMutableArray with the "cancion" object and it's saved like it's shows the first image.
EDIT 2: this is what i get trying schmidt9's answer
EDIT 3: OK, i have the json string escaped. How i have to parse now?
You should parse your output first with NSJSONSerialization:
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
// I suppose your array canciones should contain only one song object ...
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:canciones[0] options:0 error:&error];
if(error) {
// handle error ...
}
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *result = object;
[dictionary setObject:result forKey:#"canciones"];
}
Edit
Saving to database
2 options:
- if you get a prepared json string, save it directly to DB, but before you should escape quotes. See eg. here
- if you have NSDictionary:
- (NSString*)JSONStringWithDictionary:(NSDictionary*)dictionary prettyPrinted:(BOOL)prettyPrinted
{
NSJSONWritingOptions options = (prettyPrinted) ? NSJSONWritingPrettyPrinted : 0;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:options error:nil];
return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
}
After that you should escape the string too.

Taking data argument in a created NSString

How can I send data argument in an already created NSString. I have an NSDictionary:
NSArray *objectsArray=[[NSArray alloc]initWithObjects:#"item id %i",#"random id %i",nil];
NSArray *keysArray=[[NSArray alloc]initWithObjects:#"item",#"random",nil];
NSDictionary *dataDictionary=[[NSDictionary alloc]initWithObjects:objectsArray forKeys:keysArray];
Somewhere down the code I ask for the object in the NSDictionary
NSString *counterString=[dataDictionary objectForKey:#"random"];
How Can I now pass data argument into this retrieved NSString?
so my final string looks like
random id 67
NSString *finalString = [NSString stringWithFormat:counterString, digit];
If you also need to store it in your dictionary add
dataDictionary[#"random"] = finalString;
NSArray *objectsArray=[[NSArray alloc]initWithObjects:#"item id %i",#"random id %i",nil];
NSArray *keysArray=[[NSArray alloc]initWithObjects:#"item",#"random",nil];
NSDictionary *dataDictionary=[[NSDictionary alloc]initWithObjects:objectsArray forKeys:keysArray];
NSString *counterString=[dataDictionary objectForKey:#"random"];
NSString *final = [NSString stringWithFormat:counterString, 67];
dataDictionary[#"random"] = final;

JSON parsing using NSJSONSerialization in iOS

I am parsing a JSON in my code. But I am getting some unexpected issues while retrieving data of parsed JSON. So let me explain my problem.
I have to parse following JSON data using xcode. This is what data to be parsed looks like while I hit same URL in browser:
{
"RESPONSE":[
{"id":"20",
"username":"john",
"email":"abc#gmail.com",
"phone":"1234567890",
"location":"31.000,71.000"}],
"STATUS":"OK",
"MESSAGE":"Here will be message"
}
My code to reach up to this JSON data is as follow:
NSData *data = [NSData dataWithContentsOfURL:finalurl];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
If I print object json using NSLog, i.e. NSLog(#"json: %#", [json description]); it looks like:
json: {
MESSAGE = "Here will be message";
RESPONSE =(
{
email = "abc#gmail.com";
id = 20;
location = "31.000,71.000";
phone = 1234567890;
username = john;
}
);
STATUS = OK;
}
So, here I observed two things:
Sequence of keys (or nodes) (MESSAGE, RESPONSE and STATUS) is changed as compared to web response above.
The RESPONSE is get enclosed in '(' & ')' braces.
Now if I separate out values for keys MESSAGE & STATUS and NsLog them, then they get printed as proper string.
Like msgStr:Here will be message & Status:OK
But if I separate out value for RESPONSE as a dictionary and again separating sub values of that dictionary like email and username, then I can't getting those as string.
Here is the code so far I wrote:
NSMutableDictionary *response = [json valueForKey:#"RESPONSE"];
NSString *username = [response valueForKey:#"username"];
NSString *emailId = [response valueForKey:#"email"];
If I print username and emailId, then they are not getting printed as normal string, instead it outputs as:
username:(
john
)
email:(
abc#gmail.com
)
So my question is why it's not getting as a normal string? If I tried to use this variables further then they show value enclosed within '(' & ')' braces. Is this happening because of NSJSONSerialization?
First of all in your JSON response dictionary, under the key 'RESPONSE' you have a array not a dictionary and that array contains dictionary object.
So to extract username and email ID so as below
NSMutableDictionary *response = [[[json valueForKey:#"RESPONSE"] objectAtIndex:0]mutableCopy];
NSString *username = [response valueForKey:#"username"];
NSString *emailId = [response valueForKey:#"email"];
When you see braces like that, it represents an array, not a dictionary. Your JSON also shows that by enclosing the data in brackets ('[' and ']'). So:
RESPONSE =(
{
email = "abc#gmail.com";
id = 20;
location = "31.000,71.000";
phone = 1234567890;
username = john;
}
);
RESPONSE is an Array of Dictionaries. To access the data, iterate through the array:
for (NSDictionary *responseDictionary in [JSONDictionary objectForKey:#"RESPONSE"]) {
NSString *name = [responseDictionary objectForKey:#"username"];
.....
}
or grab a dictionary at an index:
NSDictionary *responseDictionary = [[JSONDictionary objectForKey:#"RESPONSE"] objectAtIndex:0];
NSString *name = [responseDictionary objectForKey:#"username"];
Whenever in doubt, log the the class:
NSLog(#"%#", [[dictionary objectForKey:#"key"] class]);
to see what is being returned from the dictionary.
1)Sequence of keys (or nodes) (MESSAGE, RESPONSE and STATUS) is
changed as compared to web response above.
The NSLog of NSDictionary is based on the sorted keys.
2)The RESPONSE is get enclosed in '(' & ')' braces.
RESPONSE =(
{
email = "abc#gmail.com";
id = 20;
location = "31.000,71.000";
phone = 1234567890;
username = john;
}
);
The RESPONSE is a key and the value is an NSArray. The array contains one NSDictionary object with keys as email, id, location, phone and username.
NOTE: () says array. {} says dictionary.
RESPONSE contains an array not an object.
So try like this:
NSMutableArray *response = [json valueForKey:#"RESPONSE"];
NSString *username = [[response objectAtIndex:0] valueForKey:#"username"];
NSString *emailId = [[response objectAtIndex:0] valueForKey:#"email"];
NSLog(#"User=>[%#] Pwd=>[%#]",username ,emailId );
pragma mark - Checking Reachability and Parsing Datas
NSString *urlString = [NSString stringWithFormat: #"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaSyD7c1IID7zDCdcfpC69fC7CUqLjz50mcls"];
NSURL *url = [NSURL URLWithString: urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
array = [[NSMutableArray alloc]init];
array = [[jsonData objectForKey:#"results"] mutableCopy];
[jsonTableview reloadData];}
pragma mark- UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellid = #"cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell = [[UITableViewCell
alloc]initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellid];
cell.textLabel.text = [[array
valueForKeyPath:#"name"]objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [[array
valueForKeyPath:#"vicinity"]objectAtIndex:indexPath.row];
NSURL *imgUrl = [NSURL URLWithString:[[array
valueForKey:#"icon"]objectAtIndex:indexPath.row]];
NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
cell.imageView.layer.cornerRadius =
cell.imageView.frame.size.width/2;
cell.imageView.layer.masksToBounds = YES;
cell.imageView.image = [UIImage imageWithData:imgData];
return cell;
}
#import.h
#interface JsonViewController :
UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UITableView *jsonTableview;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *barButton;
#property (strong,nonatomic)NSArray *array;
#property NSInteger select;
By serializing the data, u get a json object. Json object and dictionary are different a bit.
Instead of using:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
use:
NSDictionary *json = (NSDictionary*) data;

iOS parsing img tag found in JSON

I am trying to parse the file location from the following so that image can be displayed. How do I do it?
[
{
"title":"testing barcode display",
"body":"lets see if it renders \r\n\r\n",
"author":"1",
"created":"1373490143",
"nid":"5",
"Barcode":"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />"
}
]
I have a table view which displays the title tag. I need to display the entire content in the detail view. I can do everything except the Barcode tag. Please advise.
If it should be done, parse the xml
NSString *xmlString = #"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />";
GDataXMLElement *xmlElement = [[GDataXMLElement alloc]initWithXMLString:xmlString error:nil];
NSArray *attributes = [xmlElement attributes];
[attributes enumerateObjectsUsingBlock:^(GDataXMLNode * node, NSUInteger idx, BOOL *stop) {
NSLog(#"%# : %#",node.name,node.stringValue);
}];
OR
NSString *class = [[xmlElement attributeForName:#"class"] stringValue];
NSString *typeOf = [[xmlElement attributeForName:#"typeof"] stringValue];
NSString *src = [[xmlElement attributeForName:#"src"] stringValue];
NSString *alt = [[xmlElement attributeForName:#"alt"] stringValue];
NSString *title = [[xmlElement attributeForName:#"title"] stringValue];
Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
You have to convert json string in nsdictionary, so try this
SBJSON *json = [[SBJSON new] autorelease];
NSError *error;
NSDictionary *dict = [json objectWithString:YOUR_JSON_STRING error:&error];
add user this dictionary to display details in tableView

String printing incorrectly in table view after JSON parsing

I one of my apps, i parse some data from local host and print it in a table view. To get the data, the user first logs in using an alert view. The user id entered is then used to fetch the data which i parse using JSON.
There is definitely a very simple solution to this question but I can't seem to be able to fix it. The problem is that when I print the data the string comes in this format:
( "string" )
But I want it so that it just says : string
in the table view. Here is my parsing method:
- (void)updateMyBooks
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Fetch data on a background thread:
NSString *authFormatString =
#"http://localhost:8888/Jineel_lib/bookBorrowed.php?uid=%#";
NSString *string = [[NSString alloc]initWithFormat:#"%#",UserID];
NSString *urlString = [NSString stringWithFormat:authFormatString, string];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"uel is %#", url);
NSString *contents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
response1 = [contents JSONValue];
if (contents) {
// ... Parse JSON response and add objects to newBooksBorrowed ...
BookName = [[NSString alloc]init];
DateBorrowed = [[NSString alloc]init];
BookID = [[NSString alloc]init];
BookExtended = [[NSString alloc]init];
BookReturned = [[NSString alloc]init];
BookName = [response1 valueForKey:#"BookName"];
BookID = [response1 valueForKey:#"BookID"];
DateBorrowed = [response1 valueForKey:#"DateBorrowed"];
BookExtended = [response1 valueForKey:#"Extended"];
BookReturned = [response1 valueForKey:#"Returned"];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update data source array and reload table view.
[BooksBorrowed addObject:BookName];
NSLog(#"bookBorrowed array = %#",BooksBorrowed);
[self.tableView reloadData];
});
}
});
}
This is how I print it in the table view:
NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
NSLog(#"string is %#",string);
cell.textLabel.text = string;
When I use log during the parsing process, it comes out as ( "string" ) so the problem is somewhere in the parsing, at least thats what I think.
If
NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
returns something like "( string )" then the most probably reason is that
[BooksBorrowed objectAtIndex:indexPath.row]
is not a string, but an array containing a string. In that case,
NSString *string = [[BooksBorrowed objectAtIndex:indexPath.row] objectAtIndex:0];
should be the solution.
NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
string = [string stringByReplacingOccurrencesOfString:#"(" withString:#""];
string = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
string = [string stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"string is %#",string);
cell.textLabel.text = string;
EDIT:
Above code is used if it's showing text in that format in your label.
If you see that in NSlog then it's NSString inside NSArray.
You need to fetch that string first from array and then display, use code line suggested by #Martin R for that.
NSString *string = [[BooksBorrowed objectAtIndex:indexPath.row] objectAtIndex:0];

Resources