Objective-C / iOS:将对象数组转换为JSONstring

我目前正在尝试使用JSON进行互联网数据传输。 我已经成功接收JSONstring并将其转换为NSDictionary ,但还没有能够解决如何将对象的数组或字典转换为JSON表示。

我已经阅读了大量的文章和文章,解释如何创build一个键/值对的NSDictionary ,然后转换为JSON,这对于一个简单的数组工作正常,但是当你有一个数组或对象的字典时,如何实现这一点。

所以,例如,我有一个对象“联系”的数组,然后我想转换成一个JSONstring,如下所示:

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

我有一个NSMutableDictionary填充联系人对象列表:

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

然后,我尝试使用NSJSONSerialization方法转换对象的字典,但是失败并显示错误。

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

有没有人能够成功地做到这一点? 将不胜感激一些帮助或点在正确的方向。 干杯。

关于你的结构 – 你的contactsToBeSynced必须是NSDictionary类, contact应该是一个包含NSDictionary对象的NSArray ,用于不同的联系人。 顺便说一句,你有没有试过JSONKit ? 它的序列化比标准的NSJSONSerialization更好。

我解决了

我创build了一个联系对象的NSArray ,并使用SBJsonWriter使用SBJson框架:

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

我有一个JSONstring与联系人列表。

检查我的答案“ SBJsonWriter嵌套NSDictionary ”的问题。 它说明了如何正确使用SBJsonWriter。

它包括SBJsonWriter错误检查! 以及一些关于SBJsonWriter与NSDate,float等行为的build议。

摘抄:

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

一般来说,你可以为每个需要感兴趣的字段的类编写一个toDictionary方法,并将它们插入字典中。 对于在插入前转换为NSNumber的数字字段。 如果任何字段是对象,则调用该对象上的toDictionary方法,并将结果插入字典中。 如果你有一个对象的数组,你需要编写一个循环,但没有什么奇特的。

为了反转这个操作,你需要为每个类编写一个initWithDictionary方法。