我需要一个易于使用的示例库,用于将NSObjects转换为JSON并再次返回,我在网上发现了大量用于解析JSon的解析示例,但是在使用SBJSON将NSObject转换为JSON时并不过分,任何人都有不错的教程或将NSObject转换为JSON的示例代码?
使用SBJson,将对象转换为JSON字符串,您必须重写proxyForJson方法。像下面这样
SBJson
proxyForJson
.h文件,
@interface MyCustomObject : NSObject { NSString *receiverFirstName; NSString *receiverMiddleInitial; NSString *receiverLastName; NSString *receiverLastName2; } @property (nonatomic, retain) NSString *receiverFirstName; @property (nonatomic, retain) NSString *receiverMiddleInitial; @property (nonatomic, retain) NSString *receiverLastName; @property (nonatomic, retain) NSString *receiverLastName2; - (id) proxyForJson; - (int) parseResponse :(NSDictionary *) receivedObjects; }
在实施文件中,
- (id) proxyForJson { return [NSDictionary dictionaryWithObjectsAndKeys: receiverFirstName, @"ReceiverFirstName", receiverMiddleInitial, @"ReceiverMiddleInitial", receiverLastName, @"ReceiverLastName", receiverLastName2, @"ReceiverLastName2", nil ]; }
为了从JSON字符串中获取对象,您必须编写这样的parseResponse方法,
parseResponse
- (int) parseResponse :(NSDictionary *) receivedObjects { self.receiverFirstName = (NSString *) [receivedObjects objectForKey:@"ReceiverFirstName"]; self.receiverLastName = (NSString *) [receivedObjects objectForKey:@"ReceiverLastName"]; /* middleInitial and lastname2 are not required field. So server may return null value which eventually JSON parser return NSNull. Which is unrecognizable by most of the UI and functions. So, convert it to empty string. */ NSString *middleName = (NSString *) [receivedObjects objectForKey:@"ReceiverMiddleInitial"]; if ((NSNull *) middleName == [NSNull null]) { self.receiverMiddleInitial = @""; } else { self.receiverMiddleInitial = middleName; } NSString *lastName2 = (NSString *) [receivedObjects objectForKey:@"ReceiverLastName2"]; if ((NSNull *) lastName2 == [NSNull null]) { self.receiverLastName2 = @""; } else { self.receiverLastName2 = lastName2; } return 0; }