I have a string that gets it contents from a URL. Im trying to put these contents into an array that will populate a table view. Here is the code I have. What am I doing wrong here? Thanks in advance.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *strURL = [NSString stringWithFormat:#"http://10.247.245.87/index.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSArray *nameArray = [[NSArray alloc]initWithContentsOfURL:<#(NSURL *)#>;
return nameArray.count;
}
I believe there are several ways to do this, but here's a simple way to parse JSON results into arrays. Download the SBJSON framework from here
and add it to your project. Then import the JSON.h file to your #import "JSON.h". After which you can parse the string into an array using this line of code nameArray = [responseString JSONValue];.
Get SBJSON from here.
Add SBJSON to your project and Import JSON.h like so #import "JSON.h"
Parse to array like so nameArray = [responseString JSONValue];
Happy Coding!
EDIT:
you can try do something like this to check to see if you have an array of Strings after you parse the JSON into an array:
for (NSString* myString in nameArray){
NSLog(#"%#",myString);
}
if the above works out then you can get the strings from the array and fill the tableview in the cellForRowAtIndexPath delegate like so:
cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];
In this line:
return nameArray.count;
you will always get 0 because you dont wait for response from serwer.
use this after NSData..
NSArray *array = [NSJSONSerialization JSONObjectWithData:dataURL options:NSJSONReadingAllowFragments error:nil];
return array;
Related
I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);
for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.
It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);
You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];
Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file
Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS
I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray that I have to pass.
array([0] => array('latitude'=>'10.010490',
'longitude'=>'76.360779',
'altitude'=>'30.833334',
'timestamp'=>'11:17:23',
'speed'=>'0.00',
'distance'=>'0.00');
[1] => array('latitude'=>'10.010688',
'longitude'=>'76.361378',
'altitude'=>'28.546305',
'timestamp'=>'11:19:26',
'speed'=>'1.614',
'distance'=>'198.525711')
)`
and the required format is like this
[
{ "latitude":"10.010490",
"longitude":"76.360779",
"altitude":"30.833334",
"timestamp":"11:17:23",
"speed":"0.00",
"distance":"0.00"
},
{
"latitude":"10.010688",
"longitude":"76.361378",
"altitude":"28.546305",
"timestamp":"11:19:26",
"speed":"1.614",
"distance":"198.525711"
}
]
Any one have solution? Thanks in advance.
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstJsonDictionary];
[arr addObject:secondJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
The simplest and best approach !!!
To convert NSArray or NSMutableArray into jsonString you can first convert it into NSData and then further convert that into a NSString. Use this code
NSData* data = [ NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil ];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It helped me and hope it helps you as well. All the best.
I would recommend the SBJson-Framework.
Converting an NSMutableArray is as simple as NSString *jsonString = [yourArray JSONRepresentation];
Edit: Jack Farnandish is right u have to transform it into a NSDictionary before you can convert it to Json. In my example the NSMutableArray has to contain the Dictionary. The Array is only needed to create the square brackets at the beginning and the end of the string.
You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON
First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.
#import <JSONKit/JSON.h>
NSArray *array = // Your array here.
NSString *json = [array JSONString];
NSLog(#"%#", json);
JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.
Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).
Is the service you are calling a RESTful service?
If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.
I have a file named numbers.php on my ftp with the following content:
1/Brian/Red
2/Simon/Blue
3/Louise/Red
How do I get that into a table?
I need the table to show:
Brian
Simon
Loiuse
in the cells and then when you click on one of the names it takes you to a page with the colour matching the name.
I use this code when I just need to read a single line in a php file and output to textfields:
NSString *queryString = [NSString stringWithFormat: #"http://website.com/numbers.php"];
NSData *dataRequest = [NSData dataWithContentsOfURL: [ NSURL URLWithString: queryString]];
NSString *serverOutput = [[[NSString alloc] initWithData:dataRequest encoding: NSASCIIStringEncoding] autorelease];
urlTextField.text = serverOutput;
NSArray *splitString = [serverOutput componentsSeparatedByString: #"/"];
NSString *idOut = [splitString objectAtIndex: 0]; NSString *nameOut = [splitString objectAtIndex: 1]; NSString *colorOut = [splitString objectAtIndex: 2];
idTextField.text = idOut; nameTextField.text = nameOut; colorTextField.text = colorOut;
But I am a bit in doubt when it comes to multiple lines and how to get them into my table view. I assume I need to put the lines into an array?
First, I generate plist-Data on the server with the free avaliable CFPropertyList. Why, because it is verry easy to import plist-structures later.
In the app you can import data this way:
NSArray * myArray = [NSArray arrayWithContentsOfURL:[NSURL
URLWithString:#"http://url.com/foo.plist"]];
you can use NSMutableArray instead when you modifing myArray.
cheers
I get back a json of structure like
{ ResultCount =7; ResultLimit=30; ResultList=({ AlbumId=111;ArtistId=203},{AlbumId=112;ArtistId=203}); Status=0}
The ResultList is an array. How can I get the AlbumId and ArtistId in an NSArray?
Hi happy_iphone_developer,
ResultList is not a Array and it's NSDictionary.
NSString *urlDataString = [[NSString alloc] initWithData:RecievedData encoding:NSUTF8StringEncoding];
parser = [[SBJSON alloc] init];
NSError *error = nil;
NSArray *resultArray = [parser objectWithString:urlDataString error:&error];
NSString *extractString = [[resultArray valueForKey:#"ResultList"] valueForKey:#"AlbumId"];
Whatever you want to extract, use this way to extract the particular data.
Thanks.
are you wanting to make good json ? then,
{ ResultCount:7, ResultLimit:30, ResultList:[{ AlbumId:111,ArtistId:203},{AlbumId:112,ArtistId:203}]}
or you want to parse in iPhone then
http://code.google.com/p/json-framework
is good framework
Just use a JSON framework like this and you're set.
The ResultList is not a NSArray, it's a NSDictionnary.
I am trying to make a google reader app. I am able to get the subscription list in JSON format like this:
{"subscriptions":[{"id":"feed/http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss","title":"ActiveState Code: Python recipes","categories":[{"id":"user/014533032765194560dwd0/label/Programming","label":"Programming"}],"sortid":"E6312EFB","firstitemmsec":"1258141669516","htmlUrl":"http://code.activestate.com/recipes/langs/python/"},
I am interested in getting the label value (in the above case "Programming") into an array. Here is my current code:
-(BOOL)parsedSuccess {
SBJsonParser *parser = [[SBJsonParser alloc]init];
if (!receivedData) {
[self getSubscriptionList:GOOGLE_READER_SUBSCRIPTION_LIST];
}
NSMutableString *body = [[NSMutableString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:#"subscriptions"];
NSString *subTitles;
for (NSDictionary *title in subs){
subTitles = [title objectForKey:#"categories"];
NSLog(#"%#",subTitles);
}
}
return YES;
}
Can someone help me in getting the label values?
[[[[[result valueforkey:#"subscription"]objectatindex:0]valueforkey:#"categories"]objectatindex:intvalue]valueforkey:#"label"];
I just helped to make logic. Be sure to check for spelling mistakes before implementing.