Convert an object into Json using SBJson or other JSON library

本文介绍了如何使用SBJson库将自定义对象转换为JSON字符串及从JSON字符串中解析对象的方法。具体包括重写proxyForJson方法以实现对象到JSON的转换,并通过编写parseResponse方法来完成从JSON字符串到对象的解析过程。

Using SBJson, to convert a object to JSON string, you have to override the proxyForJson method. Like the following,

The .h file,

@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;
}

In the implementation file,

    - (id) proxyForJson {

       
return [NSDictionary dictionaryWithObjectsAndKeys:
            receiverFirstName
, @"ReceiverFirstName",
            receiverMiddleInitial
, @"ReceiverMiddleInitial",
            receiverLastName
, @"ReceiverLastName",
            receiverLastName2
, @"ReceiverLastName2",
            nil
];
   
}

And to get the object from the JSON string you have to write a parseResponse method like this,

- (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;
}

转载于:https://www.cnblogs.com/neozhu/archive/2012/04/04/2431890.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值