Convert xml string to NSMutableArray - iphone

NSString *xml=#"<string>aaaa</string><string>bbbb</string><string>ccccc</string>";
I Want to store text of every elemnt in NSMutableArray

Either you use xml parser which is the best option.
I suggest you TBXML and its performance is better than others
or
Try this. mtbArray is you all require
NSString *xml=#"<string>aaaa</string><string>bbbb</string><string>ccccc</string>";
xml = [xml stringByReplacingOccurrencesOfString:#"</string>" withString:#""];
NSArray *array = [xml componentsSeparatedByString:#"<string>"];
NSMutableArray *mtbArray = [array mutableCopy];
if ([mtbArray count]) {
[mtbArray removeObjectAtIndex:0];
}

You can better use the NSXMLParser for the purpose. Hope this helps you.

Related

Populate an array with the contents of a string object

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;

Converting an NSArray of Dictionaries to JSON array in 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.

How to get first value from NSMutableArray (iPhone)?

Now i am working in simple iphone application, i have stored some value in NSMutableArray like "{54.399, 196}","{-268.246, 273}".so i want to get 54.399 in first indexpath, how to get this, please help me
Thanks in Advance
It seems you have an Array of Arrays, so it would be:
[[myArray objectAtIndex:0] objectAtIndex:0];
Or using subscripting:
myArray[0][0];
Edit:
Ok you have an Array of NSStrings. To do what you want (get the 53.399) do the following:
NSString *myString = [myArray objectAtIndex:0];
NSArray *stringComponents = [myString componentsSeparatedByString:#","];
NSString *myFinalString = [stringComponents objectAtIndex:0];
With subscripting:
NSString *myFinalString = [[myArray[0] componentsSeparatedByString:#","][0];
You can use
[[arrayObj objectAtIndex:0] objectAtIndex:0];

parsing text file in objective C

i am trying to parse a text file saved in doc dir below show is the code for it
NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDirPath=[filePaths objectAtIndex:0];
NSString *filePath=[docDirPath stringByAppendingPathComponent:#"SKU.txt"];
NSError *error;
NSString *fileContents=[NSString stringWithContentsOfFile:filePath];
NSLog(#"fileContents---%#",fileContents);
if(!fileContents)
NSLog(#"error in reading file----%#",error);
NSArray *values=[fileContents componentsSeparatedByString:#"\n"];
NSLog(#"values-----%#",values);
NSMutableArray *parsedValues=[[NSMutableArray alloc]init];
for(int i=0;i<[values count];i++){
NSString *lineStr=[values objectAtIndex:i];
NSLog(#"linestr---%#",lineStr);
NSMutableDictionary *valuesDic=[[NSMutableDictionary alloc]init];
NSArray *seperatedValues=[[NSArray alloc]init];
seperatedValues=[lineStr componentsSeparatedByString:#","];
NSLog(#"seperatedvalues---%#",seperatedValues);
[valuesDic setObject:seperatedValues forKey:[seperatedValues objectAtIndex:0]];
NSLog(#"valuesDic---%#",valuesDic);
[parsedValues addObject:valuesDic];
[seperatedValues release];
[valuesDic release];
}
NSLog(#"parsedValues----%#",parsedValues);
NSMutableDictionary *result;
result=[parsedValues objectAtIndex:1];
NSLog(#"res----%#",[result objectForKey:#"WALM-FT"]);
The problem what i am facing is when i try to print lineStr ie the data of the text file it is printing as a single string so i could not able to get the contents in line by line way please help me solve this issue.
Instead use:
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
it covers several different newline characters.
Example:
NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *lineStr in values) {
// Parsing code here
}
ALso seperatedValues is over released. First one is created with alloc init, then on the next line it is replaced by the method componentsSeparatedByString. So the first one od lost without being released, that is a leak. Later the seperatedValues created by componentsSeparatedByString is released but it is already auto released by componentsSeparatedByString to that is an over release;
Solve all the retain/release/autorelease problem with ARC (Automatic Reference Counting).
Here is a version that uses convenience methods and omits over release:
NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *lineStr in values) {
NSArray *seperatedValues = [lineStr componentsSeparatedByString:#","];
NSString *key = [seperatedValues objectAtIndex:0];
NSDictionary *valuesDic = [NSDictionary dictionaryWithObject:seperatedValues forKey:key];
[parsedValues addObject:valuesDic];
}
NSLog(#"parsedValues---%#",parsedValues);
Are you sure the line separator used in your text file is \n and not \r (or \r\n)?
The problem may come from this, explaining why you don't manage to split the files into different lines.

how to retrieve a substring from a string?

I am doing Fconnect in that when a user connects to facebook I get a string like this
{"id":"100001480456987","name":"Vishnu Gupta","first_name":"Vishnu","last_name":"Gupta","link":"http:\/\/www.facebook.com\/profile.php?id=100001480456987","education":[{"school":{"id":"110885222265513","name":"st.joseph"},"type":"High School"}],"gender":"male","email":"vishu.gupta20#gmail.com","timezone":5.5,"locale":"en_US","verified":true,"updated_time":"2010-11-27T10:10:25+0000"}
Now I want to split the id name and email id of the user so that I can store it in my database.
Can someone tell me how to do it????
You don't want to split a string to get those values. Instead, you want to parse the JSON to grab data. I've used this library, it works very well: http://stig.github.com/json-framework/
Hope this helps!
EDIT: Some sample code:
NSDictionary *dict = [responseFromFacebook JSONValue];
NSString *facebookID = [dict objectForKey:#"id"];
NSString *name = [dict objectForKey:#"name"];
NSString *email = [dict objectForKey:#"email"];
this looks like JSON. Some information on JSON handling with Objective C is available at
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
Use a JSON parser. See this answer for links to stackoverflow questions about the different JSON libraries available.
Of course I'd also like to mention my own JSON parsing library, JSONKit. At the time of this writing I think it's fair to say that it's the fastest JSON parser out there.
Try this
NSDictionary *dict=[[NSDictionary alloc]init];
string=[string stringByReplacingOccurrencesOfString:#"{" withString:#""];
string=[string stringByReplacingOccurrencesOfString:#"}" withString:#""];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *seperated=[string componentsSeparatedByString:#","];
for(int index=0;index<[seperated count];index++)
{
NSArray *sub=[[seperated objectAtIndex:index] componentsSeparatedByString:#":"];
[dict setValue:[sub objectAtIndex:0] forKey:[sub objectAtIndex:1]];
}