前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Convert an object into Json using SBJson or other JSON library

Convert an object into Json using SBJson or other JSON library

作者头像
阿新
发布2018-04-12 15:59:00
6200
发布2018-04-12 15:59:00
举报
文章被收录于专栏:c#开发者

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

The .h file,

代码语言:javascript
复制
@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,

代码语言:javascript
复制
    - (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,

代码语言:javascript
复制
- (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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012-04-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档