how to convert an array into string? [duplicate] - objective-c

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.

Related

To see more than pointers in an array (objective C)

If i enumerate an array i get
<myArray: 0x71b26b0>
<myArray: 0x71b2830>
<myArray: 0x71b2900>
I could take it that myData is behind the pointers listed, but if I wanted to explicitly see (log) the contents at each address, how to do that?
I have tried the &myData to no avail
--
for the benefit of uchuugaka:
-(void)loadObservedItems{
NSString *path = [self observationFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
myArray = [unarchiver decodeObjectForKey:#"ObserveKey"];
[unarchiver finishDecoding];
} else {
myArray = [[NSMutableArray alloc] initWithCapacity:10];
}
NSLog(#" %#",myArray);
}
Add to MyClass.m:
-(NSString*)description {
NSMutableDictionary* descDict = [NSMutableDictionary dictionary];
[descDict addObject:someField forKey:#"someField"]
[descDict addObject:anotherField forKey:#"anotherField"];
[descDict addObject:yetAnotherField forKey:#"yetAnotherField"];
return [descDict description];
}
Then just use NSLog(#"myObject is %#", myObject);. Just like the big guys.
Slightly more sophisticated is to (within the method) pre-pend your class name and the object address to the result string, but that's usually unnecessary for simple debugging.
But I think you can do that like this:
return [NSString stringWithFormat:#"%# : %#", [super description], [descDict description]];

Parse multiple JSON in Objective C

Long story, short. I need to access just the parent in the JSON file.
How to parse multiple json in objective-c? )
I need to access the author > NAME from this JSON. (*removed link)
The code is:
NSURL *blogURL = [NSURL URLWithString:#"*removed link"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
// NSLog(#"%#",dataDictionary);
self.blogPosts = [NSMutableArray array];
NSArray *blogPostsArray = [dataDictionary objectForKey:#"posts"];
for (NSDictionary *bpDictionary in blogPostsArray) {
BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
blogPost.author = [bpDictionary objectForKey:#"author"];
blogPost.thumbnail = [bpDictionary objectForKey:#"thumbnail"];
blogPost.date = [bpDictionary objectForKey:#"date"];
blogPost.url = [NSURL URLWithString:[bpDictionary objectForKey:#"url"]];
[self.blogPosts addObject:blogPost];
}
How can i make it access that value ?
You should be able to use the dot notation
JSON
{
"author": {
"name" : "mckeejm"
}
}
Objective C:
blogPost.author = [bpDictionary valueForKeyPath:#"author.name"];
updated Thanks #Martin

How to parse multiple json in objective-c?

I am trying to parse JSON in objective-c but am having trouble. The example in the tutorial I am following only goes to the first level after the parent node. I am trying to get data that is a bit deeper. Any advice on how to do this?
The elements I am trying to get:
Title: data.children[i].data.title
Thumbnail: data.children[i].data.thumbnail
Json: http://www.reddit.com/r/HistoryPorn/.json
NSURL *blogURL = [NSURL URLWithString:#"http://www.reddit.com/r/HistoryPorn/.json"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError * error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.blogPosts = [NSMutableArray array];
NSArray * blogPostsArray = [dataDictionary objectForKey:#"data"];
for (NSDictionary *bpDictionary in blogPostsArray) {
BlogPost * blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
blogPost.thumbnail = [bpDictionary objectForKey:#"thumbnail"];
blogPost.url = [NSURL URLWithString:[bpDictionary objectForKey:#"url"]];
[self.blogPosts addObject:blogPost];
}
With the new syntax it should be easier to gets keys in a nested dictionaries. You can know the full keys/indexes path by just drawing a tree, remember that a dictionary starts with braces, and an array starts with brackets. For example let's retrieve the "thumbnail" and "url" value for the first entry in the children array:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(!json)
{
// Always handle eventual errors:
NSLog(#"%#",error);
return;
}
NSString* thumbnail= json[#"data"][#"children"][0][#"data"][#"thumbnail"];
NSString* url= json[#"data"][#"children"][0][#"data"][#"url"];

Dealing with NSDictionary content parsed from Flickr

I'm having an issue properly accessing an NSDictionary built from Flickr data (the flickr.photosets.getPhotos call). Instead of just showing the content of a description tag, it reads the description tag… along with some unnecessary data and quotes.
For example:
NSLog (#"Item description readout: %#", itemDescriptionPre);
yields this response:
Item description readout: {
"_content" = "This is a caption from a photo drawn through Flickr";
}
I've tried to modify the NSString with this
NSString *descripTruncated = [itemDescriptionPre substringFromIndex:17];
But it didn't causes a crash at runtime. It also doesn't address the items at the end of the item. I apologize since NSString modifications seem to be talked about a lot here, but I couldn't find circumstances that mirror mine.
Here is some more context to my code:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Storing incoming data");
NSDictionary *results = [jsonString JSONValue];
NSLog(#"Building NSDictionary.");
NSArray *photos = [[results objectForKey:#"photoset"] objectForKey:#"photo"];
NSLog(#"Building array from dictionary.");
// Loop through each entry in the dictionary...
for (NSDictionary *photo in photos)
{
NSString *title = [photo objectForKey:#"title"];
NSString *description = [photo objectForKey:#"description"];
[photoTitles addObject:title];
[photoDescriptions addObject:description];
}
NSLog(#"Nicer display for results: %# First image title: %# First image description: %#", results, [photoTitles objectAtIndex:0], [photoDescriptions objectAtIndex:0]);
[self updateDisplay];
}
-(void) updateDisplay{
NSString *capTitle = [[photoTitles objectAtIndex:0] uppercaseString];
photoTitleDisplay.text = capTitle;
NSString *itemDescriptionPre = [photoDescriptions objectAtIndex:0];
NSLog (#"Item description readout: %#", itemDescriptionPre);
}
itemDescriptionPre is actually an NSDictionary. This should work:
NSDictionary *itemDescriptionPre = [photoDescriptions objectAtIndex:0];
NSString *itemDescription = [itemDescriptionPre objectForKey:#"_content"];

JSON and 2D array

The following is encoded JSON data from a PHP webpage.
{
{
"news_date" = "2011-11-09";
"news_id" = 5;
"news_imageName" = "newsImage_111110_7633.jpg";
"news_thread" = "test1";
"news_title" = "test1 Title";
},
{
"news_date" = "2011-11-10";
"news_id" = 12;
"news_imageName" = "newsImage_111110_2060.jpg";
"news_thread" = "thread2";
"news_title" = "title2";
},
// and so on...
}
I'd like to grab one buch of info (date/id/image/thread/title), and store it as an instance of a class. However, I have no clue on how to access each object in 2D arrays.
The following is the code I've written to test if I can access them, but it doesn't work.
What would be the problem?
NSURL *jsonURL = [NSURL URLWithString:#"http://www.sangminkim.com/UBCKISS/category/news/jsonNews.php"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
SBJsonParser *parser = [[SBJsonParser alloc] init];
contentArray = [parser objectWithString:jsonData];
NSLog(#"array: %#", [[contentArray objectAtIndex:0] objectAtIndex:0]); // CRASH!!
In JSON terminology, that’s not a two-dimensional array: it’s an array whose elements are objects. In Cocoa terminology, it’s an array whose elements are dictionaries.
You can read them like this:
NSArray *newsArray = [parser objectWithString:jsonData];
for (NSDictionary *newsItem in newsArray) {
NSString *newsDate = [newsItem objectForKey:#"news_date"];
NSUInteger newsId = [[newsItem objectForKey:#"news_id"] integerValue];
NSString *newsImageName = [newsItem objectForKey:#"news_imageName"];
NSString *newsThread = [newsItem objectForKey:#"news_thread"];
NSString *newsTitle = [newsItem objectForKey:#"news_title"];
// Do something with the data above
}
You gave me a chance to checkout iOS 5 Native JSON parser, so no external libraries needed, try this :
-(void)testJson
{
NSURL *jsonURL = [NSURL URLWithString:#"http://www.sangminkim.com/UBCKISS/category/news/jsonNews.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:jsonData //1
options:kNilOptions
error:&error];
NSLog(#"First Dictionary: %#", [json objectAtIndex:0]);
//Log output:
// First Dictionary: {
// "news_date" = "2011-11-09";
// "news_id" = 5;
// "news_imageName" = "newsImage_111110_7633.jpg";
// "news_thread" = " \Uc774\Uc81c \Uc571 \Uac1c\Ubc1c \Uc2dc\Uc791\Ud574\Ub3c4 \Ub420\Uac70 \Uac19\Uc740\Ub370? ";
// "news_title" = "\Ub418\Ub294\Uac70 \Uac19\Uc9c0?";
// }
//Each item parsed is an NSDictionary
NSDictionary* item1 = [json objectAtIndex:0];
NSLog(#"Item1.news_date= %#", [item1 objectForKey:#"news_date"]);
//Log output: Item1.news_date= 2011-11-09
}