JSON iOS parsing string - ios

{"response":[33689822,64091979,69682048,74160161]}
-
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSLog(#"okRequest|| %#",responseString);
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithString:responseString];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
//all other func..
NSLog(#"%# ", status);///This func prints only "response"
}
}
How I can get array of numbers in "response"? (33689822,64091979,69682048,74160161)

Try this:
for (NSNumber *number in [statuses objectForKey:#"response"]) {
NSLog(#"%#", number);
}

You can either parse the JSON data yourself, or better, use a library like TouchJSON to do it for you.

Try using JSONFragmentValue directly.
NSString *response=[request responseString];
id usableResp = [response JSONFragmentValue];

Related

Deserialise JSON String in Objective C

I received NSData object data from REST API. That contains JSON data which I want to parse.
{
JsonResult = "[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
}
This statement gave me the result as a String like below which I am not able to parse as JSON.
myData = [data valueForKey:#"JsonResult"];
"[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
When I try to pass this mydata to JSONSerialization the code crashes.
How do I cast the above string to NSDictionary so that I can parse them and use the values of IsAuth and User.?
Code:
[LDService authenticateUser:Uname.text passwordString:Password.text completeBlock:^(NSData * data){
NSError *error;
NSData *jsonData;
NSString *jsonString = nil;
NSMutableDictionary *jsonDict;
if([NSJSONSerialization isValidJSONObject:data])
{
jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
NSLog(#"Formatted string %#",formattedString);
[jsonDict setObject:formattedString forKey:#"JsonResult"];
NSLog(#"Parsed json %#",jsonDict);
}];
Pass your data as data
NSError *error;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:data])
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
then replace occurance of #"\\\" with #"'"
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
then use this formattedString.
I have investigates your json file from Json formatter & Validator, there are lots of error in your json file, so first check your file from this validator and this formatter gives you error with description. Re-build your json file, if you still getting any problem then ask.

iOS-error in parsing the data

In my app, I am parsing the data using JSON
NSString * urlString=[NSString stringWithFormat:#"http://userRequest?userid=bala#gmail.com&latitude=59.34324&longitude=23.359257"];
NSURL * url=[NSURL URLWithString:urlString];
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError * error;
NSURLResponse * response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * outputData=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",outputData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:outputData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
After this code executes, In my log it is printed as
({
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},
{
latitude = "80.000000000000000";
longitude = "30.000000000000000";
username = arun;
})
But while running, the app crashes, as
'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x910d8d0'
I think your problem is, that jsonParser objectWithString returns an array with dictionaries in it not dictionaries itself.
Try the following:
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
for(NSDictionary *dict in jsonData) {
NSLog(#"%#",dict);
}
Does that work for you ?
Your reponse is NSArray which contains NSDictionary. So frst get dictionary from array then access value. Also Your json not look like correct.
for (NSDictionary *dict in responseArray) {
double latitude = [dict[#"latitude"]doubleValue];
double longitude = [dict[#"latitude"] longitude];
NSString* name = dict[#"username"];
}
1. First of all you are getting NSArray in JSON
JSON Starts with "(" means NSArray
JSON Starts with "{" means NSDictionary
Here you are getting NSArray which has collection of NSDictionary,
{
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},...
2."success" key is not present in the JSON..
Fix
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
If([jsonData count]>0){
// Has some data
// Iterate NSDictionary and get data here
}
else{
// No Data
}
some where you are getting data from nsarray with using some object key. that key is invalid to fetching data from array

Parse JSON using NSURLConnection

I am using Bing Search API and able to successfully parse the xml but not JSON.Below is the code to both parse xml and JSON,when I nslog the output of the JSON it shows "null" I don't know how to proceed from here.
-(void)searchBing:(NSString *)text{
//NSString *query1 = #"San Francisco Baseball";
NSString *query = [NSString stringWithFormat: #"'%#'",text];
//NSString *query = query1;
NSString *format = #"atom";
NSString *market = #"'en-us'";
//NSInteger top = 2;
NSMutableString *fullURL = [NSMutableString stringWithCapacity:256];
[fullURL appendString:URL];
[fullURL appendFormat:#"Web?$format=%#", format];
[fullURL appendFormat:#"&Query=%#",
[query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[fullURL appendFormat:#"&Market=%#",
[market stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// [fullURL appendFormat:#"&$top=%d", top];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:
[self getRequest:fullURL] delegate:self];
if (connection)
{
NSLog(#"Connection established");
}
else
{
NSLog(#"Connection failed");
}
}
Below where am parsing both xml(successful) and JSON(unsuccessful)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
// convert to JSON
NSLog(#"Finished loading: Received %d bytes of data",[self.responseData length]);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
[parser setDelegate: self];
[parser parse];
NSLog(#"XMl == %#",parser);
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
NSLog(#"json data = %#",res);//getting null
}
Am using Base_64 encoding and to all viewers nothing wrong with query because getting correct information via xml parser.But I want response in JSON.
Structure sample
{
"SearchResponse":{
"Version":"2.2",
"Query":{
"SearchTerms":"testign"
},
"Spell":{
"Total":1,
"Results":[
{
"Value":"testing"
}
]
},
"Web":{
"Total":5100,
"Offset":0,
"Results":[
{
"Title":"Testign part 2 - Tiernan OTooles Programming Blog",
"Description":"If this works, it means nothing really, but i have managed to build a .TEXT blog posting app. could be handy if i move my main blog to .TEXT, which i am thinking about..",
"Url":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DisplayUrl":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DateTime":"2008-10-21T05:08:05Z"
}
]
}
}
}
From your post:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
.
.
.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
It looks like you're trying to use the same data as XML and JSON. You can't do that. The data returned from the server is in one form OR the other. It won't be both.

Create NSDictionary with keys and values when selected UICollectionViewCell

I have a UICollectionView with thumbnails. When user selects one or multiple images at same time, I have to create NSDictionary with keys and values. Key has to be a specific name. This is the final result I need to get.
(
image[0] = 75829457,
image[1] = 03480923,
image[2] = 58924589
)
Values here are obviously image ids. How can I do that? I need to send that NSDictionary via POST request, which is not a problem.
Any help would be appreciated.
Thank you.
create a method to get ImageDictionary
- (NSDictionary *) dictionaryWithImageArray:(NSArray *)imageArrayID
{
NSMutableDictionary *imageDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<[imageArrayID count]; i++) {
[imageDict setObject:[imageArrayID objectAtIndex:i] forKey:[NSString stringWithFormat:#"image[%d]",i]];
}
return imageDict;
}
Convert that dict to json string
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:<Dict from above>
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString= nil;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
jsonString = #"";
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
Set Http Body for your request
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
In your controller, declare a member variable NSMutableString *mutableString. Initialize mutableString in your init method to be empty.
- (void)collectionView:(UICollectionView *)aCollectionView didSelectItemAtIndexPath:(NSIndexPath)indexPath {
NSString *key = [NSString stringWithFormat:#"image[%d]", [indexPath row]];
NSString *value = // get the picture id
NSString *parameter = [NSString stringWithFormat:#"%#=%#", key, value];
if ([mutableString length] != 0)
[mutableString appendString:#"&"];
[mutableString appendString:parameter];
}
Then use an IBAction to confirm the selections, construct your POST request and send it, and then empty the mutable string.

Url correct but the dictionary is null

I have to download data using JSON, the url is correct (tested on chrome) but I get an empty dictionary. Where did I go wrong?
NSLog(#"'url is %#", stringUrl); //correct
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringUrl]];
NSHTTPURLResponse __autoreleasing *response = nil;
NSError __autoreleasing *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// the result is:
/* <280d0a0d 0a0d0a0d 0a0d0a0d 0a0d0a7b 22636f6d 6d6f6e22 3a7b2261 636b223a
224f4b22 2c226661 756c7443 6f646522 3a6e756c 6c2c2266 61756c74 53747269
6e67223a 6e756c6c 7d2c2274 6f74616c 223a3138 362c2270 61676522 3a312c22
.......*/
NSString *str = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#" STRING IS %#", str);
//the string is correct
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSLog (#"The parser is %#", parser);
//The parser is <SBJsonParser: 0x8877400>
NSDictionary *object = [parser objectWithData: result];
NSLog(#" The dictionary is %#", object);// The dictionary is null
The result of string:
NSString *str = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#" THE STRING IS %#", str);
/* ({"common":
{"ack":"OK",
"faultCode":null,
"faultString":null},
"total":8,
"page":1,
"limit":15,
"products":[{"name":"BANANE SOLIDAL BIOLOGICAL - cartone/estero/2^
cat.",
"code":"52436",
"anabel":"264342000",
"hasPezzature":true,
"pezzatureList":
[{"weight":700.000,"unit":"Gr","formatted":"700GR"}],
"disponible":true,
"promotionImage":null},
{"name":"KIWI IT 105-120 II^ VAS
500GR",
"code":"52094",
"anabel":"393261000",
"hasPezzature":true,
"pezzatureList":
[{"weight":500.000,"unit":"GR","formatted":"500GR"}],
"disponible":true,
"promotionImage":null},
........
.........]});*/
I put the formatting so to be readable, in fact the returned data is all on one line
There is a "(" and ")" at the starting and ending of the JSON response when you try to cast it in a NSDictionary or NSArray, it doesnt recognize it and hence goes empty. So to get it parsed you'll need to add this:
str = [[str stringByReplacingOccurrencesOfString:#"(" withString:#""] stringByReplacingOccurrencesOfString:#")" withString:#""];
before
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSLog (#"The parser is %#", parser);
//The parser is <SBJsonParser: 0x8877400>
NSDictionary *object = [parser objectWithData: result];
NSLog(#" The dictionary is %#", object);// The dictionary is null

Resources