Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...