2

所以我的 JSON 请求应该类似于:

{ 
   "MyDictionary" : ["some values"], 
   "RegularValue" : "regularValue",
}

所以我目前所做的是:

NSDictionary *myDict = @{@"Blah" : @"1", @"Yadayada" : @"2"}; 
NSDictionary *jsonDict = @{"MyDictionary" : myDict, "RegularValue" : "someValue"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];

所以这很好用。我遇到的问题是,我想要做的是使用 NSObject 的自定义子类并将其序列化为 JSON,而不是手动创建 MyDictionary。我基本上必须为我的自定义 NSObject 的属性手动创建 NSDictionary 并将其放入 NSJSONSerialization 方法中。但我想知道是否有更好的方法来做到这一点?谢谢。

4

2 回答 2

0

也许这可以帮助JLCustomClassDisassembler

它迭代自定义对象以获取属性。这将为您提供字典/数组,然后只需使用 sbjson/jsonkit 或您喜欢的任何东西来构建您的 json 字符串。

于 2013-05-08T03:41:54.120 回答
-3

To achieve this you would need to create your own custom NSObject class with attributes and more and still have a custom method to serialize the object, similar to the way toString works on java, on Objective-C you would need to implement

- (NSString *)description

on your method and then return the serialized object.

on this method you could read all the attributes of the current object and then somehow serialize them, this thread presents a nice sample code to read all the attributes of a certain Object

Get an object properties list in Objective-C

于 2013-01-22T21:32:07.530 回答