Convert an iOS Objective C Object to a JSON String

Convert an iOS objective c object to a JSON string

EDIT: I have made a dummy app that should be a good example for you.

I create a Message class from your code snippet;

//Message.h
@interface Message : NSObject {
NSString *from_;
NSString *date_;
NSString *msg_;
}

@property (nonatomic, retain) NSString *from;
@property (nonatomic, retain) NSString *date;
@property (nonatomic, retain) NSString *msg;

-(NSDictionary *)dictionary;

@end

//Message.m
#import "Message.h"

@implementation Message

@synthesize from = from_;
@synthesize date = date_;
@synthesize msg = mesg_;

-(void) dealloc {
self.from = nil;
self.date = nil;
self.msg = nil;
[super dealloc];
}

-(NSDictionary *)dictionary {
return [NSDictionary dictionaryWithObjectsAndKeys:self.from,@"from",self.date, @"date",self.msg, @"msg", nil];
}

Then I set up an NSArray of two messages in the AppDelegate. The trick is that not only does the top level object (notifications in your case) need to be serializable but so do all the elements that notifications contains: Thats why I created the dictionary method in the Message class.

//AppDelegate.m
...
Message* message1 = [[Message alloc] init];
Message* message2 = [[Message alloc] init];

message1.from = @"a";
message1.date = @"b";
message1.msg = @"c";

message2.from = @"d";
message2.date = @"e";
message2.msg = @"f";

NSArray* notifications = [NSArray arrayWithObjects:message1.dictionary, message2.dictionary, nil];
[message1 release];
[message2 release];


NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsonString);

@end

The output when I run the application is thus:

2012-05-11 11:58:36.018 stack[3146:f803] JSON Output: [
{
"msg" : "c",
"from" : "a",
"date" : "b"
},
{
"msg" : "f",
"from" : "d",
"date" : "e"
}
]

ORIGINAL ANSWER:

Is this the documentation you are looking for?

IOS - How to convert json string into object

Your response is not in proper json format. First add the below line to remove the extra empty result string by following line:

yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];

Then, Try out the below code:

    yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];

NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *error = nil;
NSDictionary *responseObj = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];

if(! error) {
NSArray *responseArray = [responseObj objectForKey:@"result"];
for (NSDictionary *alternative in responseArray) {
NSArray *altArray = [alternative objectForKey:@"alternative"];
for (NSDictionary *transcript in altArray) {
NSLog(@"transcript : %@",[transcript objectForKey:@"transcript"]);
}
}

} else {
NSLog(@"Error in parsing JSON");
}

How to convert class object to json string in objective c

The dataWithJSONObject:options:error: method only works on objects that NSJSONSerialization knows how to convert to JSON. That means:

  • The top-level object must be an NSArray or NSDictionary
  • Objects contained must be instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • Dictionary keys must be NSStrings
  • Numbers must not be infinite or NaN.

You need to convert to a dictionary or array representation to use this method.

How to convert data string to json object and string in iOS?

Use this

NSString *str=@"{\"Data\": [{\"ID\":\"1\",\"Name\":\"Raj\"},{\"ID\":\"2\",\"Name\":\"Rajneesh\"}]}";

NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];

NSMutableArray *dataArr=[dict valueForKey:@"Data"];
for (NSDictionary *userData in dataArr) {
NSLog(@"Id:%@ Name:%@",[userData valueForKey:@"ID"],[userData valueForKey:@"Name"]);
}

From object to json

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

Here you can check it Link

Collections *current = _raccolte[_currentCell];
current.label = [[alertView textFieldAtIndex:0] text];
current.datetime_last_update =
[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];

NSMutableArray *coll = [[NSMutableArray alloc] init];
[coll addObject:current.label];
[coll addObject:current.datetime_last_update];

NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:coll
options:NSJSONWritingPrettyPrinted
error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];

NSLog(@"JSON Output: %@", jsonString);

IOS/Objective-C: Convert NSArray of Custom Objects to JSON

Like you said, NSJSONSerialization only understands Dictionaries and Arrays. You'll have to provide a method in your custom class that converts its properties into a Dictionary, something like this:

@interface Offers 
@property NSString* title;
-(NSDictionary*) toJSON;
@end

@implementation Offers
-(NSDictionary*) toJSON {
return @{
@"title": self.title
};
}
@end

then you can change your code to

NSArray <Offers *> *offers = [self getOffers:self.customer];
NSMutableArray<NSDictionary*> *jsonOffers = [NSMutableArray array];
for (Offers* offer in offers) {
[jsonOffers addObject:[offer toJSON]];
}
NSError *error;
//Following line crashes
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:jsonOffers
options:kNilOptions
error:&error];

Serialize and Deserialize Objective-C objects into JSON

It sounds like you're looking for a serialization library that can let you convert objects of your own custom classes into JSON, and then reconstitute them back. Serialization of property-list types (NSArray, NSNumber, etc.) already exists in 3rd party libraries, and is even built into OS X 10.7 and iOS 5.

So, I think the answer is basically "no". I asked this exact question a month or two ago on the cocoa-dev mailing list, and the closest I got to a hit was from Mike Abdullah, pointing to an experimental library he'd written:

https://github.com/mikeabdullah/KSPropertyListEncoder

This archives objects to in-memory property lists, but as I said there are already APIs for converting those into JSON.

There's also a commercial app called Objectify that claims to be able to do something similar:

http://tigerbears.com/objectify/

It's possible I'll end up implementing what you're asking for as part of my CouchCocoa library, but I haven't dived into that task yet.

https://github.com/couchbaselabs/CouchCocoa

iOS - Convert a JSON object to an ordered array

You can change your JSON data to

[
{"af":"Afghanistan"},
{"al":"Albania"},
{"dz":"Algeria"},
{"as":"American Samoa"},
{"ad":"Andorra"},
{"ao":"Angola"},
{"ai":"Anguilla"},
...
]

Then use the code like:

NSURL *jsonPath = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"json"];
NSData *countriesJSON = [NSData dataWithContentsOfURL:jsonPath];
NSMutableArray *countryArray = [NSJSONSerialization JSONObjectWithData: countriesJSON options:NSJSONReadingMutableContainers error:nil];

The JSON is converted to a ordered array called countryArray. the elements of the countryArray is a NSDictionary instance.

Generate JSON string from NSDictionary in iOS

Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).

@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end

.

@implementation NSDictionary (BVJSONString)

-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];

if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end

.

@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end

.

@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];

if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end


Related Topics



Leave a reply



Submit