How to convert NSArray into NSString - iphone

How to convert NSArray into NSString in objective-c?

Bearing in mind that you don't say what's in the NSArray, you can do this:
NSArray *arr = [NSArray arrayWithObjects: #"foo", #"bar", #"baz"];
[arr componentsJoinedByString: #","]

Aternatively to Frank's method, which works pretty well, you could also do
NSString *myArrayString = [array description];
The default implementation of description on NSArray will print out the contents in a neatly formatted fashion.

This is how I have converted my NSArray to NSString
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:aArray options:kNilOptions error:&error];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Swift 3.0 latest updates
let string = array.componentsJoined(by: ",")
you can used any separator in function which you want to separate the array elements currently in above example is ",".

Related

create a json string from NSArray

In my iPhone aplication I have a list of custom objects. I need to create a json string from them. How I can implement this with SBJSON or iPhone sdk?
NSArray* eventsForUpload = [app.dataService.coreDataHelper fetchInstancesOf:#"Event" where:#"isForUpload" is:[NSNumber numberWithBool:YES]];
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *actionLinksStr = [writer stringWithObject:eventsForUpload];
and i get empty result.
This process is really simple now, you don't have to use external libraries,
Do it this way, (iOS 5 & above)
NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I love my categories so I do this kind of thing as follows
#implementation NSArray (Extensions)
- (NSString*)json
{
NSString* json = nil;
NSError* error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return (error ? nil : json);
}
#end
Although the highest voted answer is valid for an array of dictionaries or other serializable objects, it's not valid for custom objects.
Here is the thing, you'll need to loop through your array and get the dictionary representation of each object and add it to a new array to be serialized.
NSString *offersJSONString = #"";
if(offers)
{
NSMutableArray *offersJSONArray = [NSMutableArray array];
for (Offer *offer in offers)
{
[offersJSONArray addObject:[offer dictionaryRepresentation]];
}
NSData *offersJSONData = [NSJSONSerialization dataWithJSONObject:offersJSONArray options:NSJSONWritingPrettyPrinted error:&error];
offersJSONString = [[NSString alloc] initWithData:offersJSONData encoding:NSUTF8StringEncoding] ;
}
As for the dictionaryRepresentation method in the Offer class:
- (NSDictionary *)dictionaryRepresentation
{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
[mutableDict setValue:self.title forKey:#"title"];
return [NSDictionary dictionaryWithDictionary:mutableDict];
}
Try like this Swift 2.3
let consArray = [1,2,3,4,5,6]
var jsonString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(consArray, options: NSJSONWritingOptions.PrettyPrinted)
{
jsonString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
Try like this,
- (NSString *)JSONRepresentation {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithObject:self];
if (!json)
[jsonWriter release];
return json;
}
then call this like,
NSString *jsonString = [array JSONRepresentation];
Hope it will helps you...
I'm a bit late to this party, but you can serialise an array of custom objects by implementing the -proxyForJson method in your custom objects. (Or in a category on your custom objects.)
For an example.

Break String that came from Json

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}
You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.
Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

iPhone:Adding multiple nsdictionaries into NSArray

I need to add multiple NSDictionaries into an NSArray to get a JSON message.I want to get this string.
This is my code:
for (int i=0;i<[ids count]; i++)
{
[dict setObject:[NSString stringWithFormat:#"%#",personName] forKey:#"customerName"];
NSArray *array = [NSArray arrayWithObject:cartDict];
[dict setObject:array forKey:#"OrderDetails"];
}
NSString *request1 = [dict JSONRepresentation];
//convert object to data
NSData *jsonData = [NSData dataWithBytes:[request1 UTF8String] length:[request1 length]];
//NSData* jsonData = [NSJSONSerialization dataWithJSONObject:req options:NSJSONWritingPrettyPrinted error:nil];
//print out the data contents
json1 = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
You are just changing the values in the same instance of the cartDict. If you want to have more than one cartDict in your array, alloc and init a new NSDictionary and then add that to the array (don't forget to release after if you aren't using ARC!).

JSON parsing issue

My code:
NSString *jsonString;
jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
NSLog(#"%#",jsonString);
// Build an array from the dictionary for easy access to each entry
NSArray *places = [results objectForKey:#"description"];
I am not getting the result i wanted.
When I debug the code I am getting 2 key/value pair & 0 object for NSArray places.
It is correct that you have 2 key/value pairs. The top two keys intact are "predictions" and "status". So you must first of all extract predictions (it's an array):
NSArray *predictions = [results objectForKey:#"predictions"];
and then iterate over it; also note that "description" is a string and to get the places you must split it using the "," separator:
for(NSDictionary *aPrediction in predictions) {
NSString *description = [aPrediction objectForKey:#"description"];
NSArray *placesInDescription = [description componentsSeparatedByString:#","];
}
maybe you should use:
NSArray *places = [results valueForKey:#"predictions"];
Works for me without any problems with JSON Kit!
NSString *jsonString;
NSData *responseData = [NSData dataWithContentsOfURL: [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=solapur&sensor=true&key=AIzaSyC0K5UhV_BWmXhncIZEnbh-WG2RVQVgfdY"]];
jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString objectFromJSONString];
// Build an array from the dictionary for easy access to each entry
NSArray *places = [results valueForKey:#"predictions"];
NSLog(#"places %#", places);

Cannot access a dictionary created with TouchJSON

I am trying to use TouchJSON and here is what I have done to test it :
NSString *jsonString = #"{\"firtname\": \"Matthieu\",\"lastname\": \"Ravey\",\"age\": 22}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSString *firstname = [dictionary objectForKey:#"firstname"];
NSLog(#"%#", firstname);
But it logs null instead of Matthieu, what am I missing ?
Thanks
In your json string - NSString *jsonString = #"{\"firtname\": \"Matthieu\",\"lastname\": \"Ravey\",\"age\": 22}"; it says firtstring.
Try accessing this dictionary with same keys !
So the change would be -
NSString *firstname = [dictionary objectForKey:#"firtname"];