我在服务器端广泛使用Jackson从POJO转换为JSON,并且想知道是否有类似的Objective C / iPhone SDK库,反之亦然。 Objective C确实提供了反射,因此应该可以制作类似Jackson的东西。
答案 0 :(得分:4)
您可以尝试GoldenFleece,它使用受Jackson启发的约会配置模式在JSON和Objective-C对象之间进行转换。
答案 1 :(得分:2)
new iOS 5 APIs为阅读/编写JSON提供了很好的便利。这些本质上是你可以在iOS 4中使用的TouchJSON library的重新散列。虽然我没有看到很多将从示例有效负载生成POCO对象,但是你可以创建只是一个外观的类。上述库将返回的NSDictionary
实例。
例如:
@interface PBPhoto : NSObject {
NSDictionary* data_;
}
@property (nonatomic, retain, readonly) NSDictionary *data;
- (NSString*) photoId;
- (NSString*) userId;
- (NSString*) user;
- (NSString*) title;
- (id) initWithData:(NSDictionary*)data;
@end
实现:
#import "PBPhoto.h"
#define PHOTO_ID @"id"
#define USER_ID @"user_id"
#define USER @"user"
#define TITLE @"title"
@implementation PBPhoto
@synthesize data = data_;
- (id) initWithData:(NSDictionary*)data {
if ((self = [super init])) {
self.data = data;
}
return self;
}
- (NSString*) photoId {
return [super.data objectForKey:PHOTO_ID];
}
- (NSString*) userId {
return [self.data objectForKey:USER_ID];
}
- (NSString*) user {
return [self.data objectForKey:USER];
}
- (NSString*) title {
return [self.data objectForKey:TITLE];
}
- (void) dealloc {
[data_ release];
[super dealloc];
}
@end
答案 2 :(得分:1)
Objective-C提供的反射可能是年度的低估,但很多东西只能通过低级C运行时暴露,因此有点迟钝。
假设您想要获取一个任意对象并将其转换为JSON,可能聪明的是创建一个NSDictionary
作为中介,然后将其传递给NSJSONSerialization
(或者构造字符串)你自己,因为所有的第三方图书馆都是非常重量级的,因为能够反序列化的负担。)
所以,例如:
- (NSDictionary *)dictionaryOfPropertiesForObject:(id)object
{
// somewhere to store the results
NSMutableDictionary *result = [NSMutableDictionary dictionary];
// we'll grab properties for this class and every superclass
// other than NSObject
Class classOfObject = [object class];
while(![classOfObject isEqual:[NSObject class]])
{
// ask the runtime to give us a C array of the properties defined
// for this class (which doesn't include those for the superclass)
unsigned int numberOfProperties;
objc_property_t *properties =
class_copyPropertyList(classOfObject, &numberOfProperties);
// go through each property in turn...
for(
int propertyNumber = 0;
propertyNumber < numberOfProperties;
propertyNumber++)
{
// get the name and convert it to an NSString
NSString *nameOfProperty = [NSString stringWithUTF8String:
property_getName(properties[propertyNumber])];
// use key-value coding to get the property value
id propertyValue = [object valueForKey:nameOfProperty];
// add the value to the dictionary —
// we'll want to transmit NULLs, even though an NSDictionary
// can't store nils
[result
setObject:propertyValue ? propertyValue : [NSNull null]
forKey:nameOfProperty];
}
// we took a copy of the property list, so...
free(properties);
// we'll want to consider the superclass too
classOfObject = [classOfObject superclass];
}
// return the dictionary
return result;
}
然后,您可以在+ dataWithJSONObject:options:error:
上使用NSJSONSerialization
和返回的词典。
换句话说,我猜你会使用键值编码setValue:forKey:
方法,通过allKeys
和valueForKey:
从字典中获取键和值。