简体   繁体   English

Objective-C / iOS:将对象数组转换为JSON字符串

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

I am currently experimenting with the use of JSON for internet data transfer. 我目前正在尝试使用JSON进行互联网数据传输。 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. 我已经成功接收了JSON字符串并将其转换为NSDictionary ,但是还无法确定如何将对象的数组或字典转换为JSON表示形式。

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. 我已经阅读了许多文章和文章,这些文章和文章解释了如何创建键/值对的NSDictionary ,然后将其转换为JSON,这对于简单的数组来说效果很好,但是当您拥有对象的数组或字典时如何实现此目的。

So for example, I have an array of objects "contact", which I would then like to transform into a JSON string as such: 因此,例如,我有一个对象数组“ contact”,然后将其转换为这样的JSON字符串:

"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 ,它填充联系人对象的列表:

    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. 然后,我尝试使用NSJSONSerialization方法转换对象的字典,但是它失败并出现错误。

    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. 干杯。

About your structure - your contactsToBeSynced must be of NSDictionary class, and contact should be an NSArray containing NSDictionary objects for different contacts. 关于你的结构-你contactsToBeSynced必须是NSDictionary类,并且contact应该是一个NSArray含有NSDictionary对象,对不同的联系人。 By the way, have you tried JSONKit ? 顺便说一句,您尝试过JSONKit吗? It's serialization works better than standard NSJSONSerialization . 它的序列化比标准NSJSONSerialization更好。

I worked it out... 我解决了...

I created an NSArray of contact objects and using the SBJson framework with SBJsonWriter: 我创建了一个接触对象的NSArray ,并将SBJson框架与SBJsonWriter结合使用:

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

I got a JSON string with a list of contacts. 我得到了带有联系人列表的JSON字符串。

Check my answer to the '' SBJsonWriter Nested NSDictionary '' question. 检查我对“ SBJsonWriter嵌套NSDictionary ”问题的回答。 it illustrate how to properly use SBJsonWriter. 它说明了如何正确使用SBJsonWriter。

It includes SBJsonWriter error checking! 它包括SBJsonWriter错误检查! and some pieces of advise about SBJsonWriter behaviour with NSDate, float, etc.. 以及有关NSDate,float等的SBJsonWriter行为的一些建议。

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];

In general, you write a toDictionary method for each class which takes the fields of interest and inserts them in a dictionary. 通常,您为每个类编写一个toDictionary方法,该方法获取感兴趣的字段并将其插入字典中。 For numeric fields you convert to NSNumber before inserting. 对于数字字段,请在插入之前将其转换为NSNumber。 If any field is an object, you call the toDictionary method on that object and insert the result in your dictionary. 如果任何字段是对象,则在该对象上调用toDictionary方法,然后将结果插入字典中。 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. 要反转操作,请为每个类编写一个initWithDictionary方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM