rosst400
rosst400

Reputation: 573

Objective-C / iOS: Converting an array of objects to JSON string

I am currently experimenting with the use of JSON for internet data transfer. I have been successful in receiving a JSON string and converting it into an NSDictionary, but have not been able to work out how to convert an array or dictionary of objects into a JSON representation.

I have read a number of posts and articles which explain how to create a NSDictionary of key/value pairs and then convert to JSON, which works fine for a simple array, but how do you achieve this when you have an array or dictionary of objects.

So for example, I have an array of objects "contact", which I would then like to transform into a JSON string as such:

"contacts":{
    "contact":[
    {
        "id":"1"
        "first_name":"john",
        "last_name":"citizen",
        "phone":"9999 9999"
    }
    {
        "id":"1"
        "first_name":"jane",
        "last_name":"doe",
        "phone":"8888 8888"
    }
    ]
 }

I have a NSMutableDictionary which is populate a list of contact objects:

    NSMutableDictionary* contactsToBeSynced = [[NSMutableDictionary alloc] init];
    //Populate dictionary with contact objects.
    contactsToBeSynced = self.getNonSynchronisedData;

I then attempt to transform the dictionary of objects with the NSJSONSerialization method, but it fails with an error.

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

Has anyone been able to successfully do this? Would greatly appreciate some help or a point in the right direction. Cheers.

Upvotes: 5

Views: 12111

Answers (4)

Hot Licks
Hot Licks

Reputation: 47729

In general, you write a toDictionary method for each class which takes the fields of interest and inserts them in a dictionary. For numeric fields you convert to NSNumber before inserting. If any field is an object, you call the toDictionary method on that object and insert the result in your dictionary. If you have an array of objects you need to write a loop, but it's nothing exotic.

To reverse the operation you write an initWithDictionary method for each class.

Upvotes: 0

Pascal
Pascal

Reputation: 16631

Check my answer to the '' SBJsonWriter Nested NSDictionary '' question. it illustrate how to properly use SBJsonWriter.

It includes SBJsonWriter error checking! and some pieces of advise about SBJsonWriter behaviour with NSDate, float, etc..

Excerpt:

NSDictionary* aNestedObject = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"nestedStringValue", @"aStringInNestedObject",
                                      [NSNumber numberWithInt:1], @"aNumberInNestedObject",
                                 nil];

NSArray * aJSonArray = [[NSArray alloc] initWithObjects: @"arrayItem1", @"arrayItem2", @"arrayItem3", nil];

NSDictionary * jsonTestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"stringValue", @"aString",
                                     [NSNumber numberWithInt:1], @"aNumber",
                                     [NSNumber numberWithFloat:1.2345f], @"aFloat",
                                     [[NSDate date] description], @"aDate",
                                     aNestedObject, @"nestedObject",
                                     aJSonArray, @"aJSonArray",
                                     nil];

Upvotes: 0

rosst400
rosst400

Reputation: 573

I worked it out...

I created an NSArray of contact objects and using the SBJson framework with SBJsonWriter:

SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:arr];

I got a JSON string with a list of contacts.

Upvotes: 1

Kyr Dunenkoff
Kyr Dunenkoff

Reputation: 8090

About your structure - your contactsToBeSynced must be of NSDictionary class, and contact should be an NSArray containing NSDictionary objects for different contacts. By the way, have you tried JSONKit? It's serialization works better than standard NSJSONSerialization.

Upvotes: 5

Related Questions