使用SBJson或其他Json库将对象转换为Json



我需要一个易于使用的库白色的例子转换NSObject到JSON再回来,我在网上发现了大量的解析JSON的例子,但没有太多的转换NSObject到JSON使用SBJSON,任何人有一个很好的教程或样例代码转换NSObject到JSON ?

使用SBJSON,这真的很简单。

NSString *myDictInJSON = [myDict JSONRepresentation];
NSString *myArrayInJSON = [myArray JSONRepresentation];

当然,数组的另一个方向是:

NSDictionary *myDict = [myDictInJSON JSONValue];
NSArray *myArray = [myArrayInJSON JSONValue];

使用SBJson,将对象转换为JSON字符串,您必须覆盖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方法,像这样,

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

从JSON字符串到对象:

SBJsonParser *parser = [[SBJsonParser alloc] init];
// gives array as output
id objectArray = [parser objectWithString:@"[1,2,3]"]; 
// gives dictionary as output
id objectDictionary = [parser objectWithString:@"{"name":"xyz","email":"xyz@email.com"}"]; 

从对象到JSON字符串:

SBJsonWriter *writer = [[SBJsonWriter alloc] init];
id *objectArray = [NSArray arrayWithObjects:@"Hello",@"World", nil];
// Pass an Array or Dictionary object.
id *jsonString = [writer stringWithObject:objectArray]; 

最新更新