开发者

iphone, SBJsonWriter .. converting an object

开发者 https://www.devze.com 2023-03-09 05:12 出处:网络
I want to post a json object to a request. But JSONWriter doesn\'t seem to convert my object, don\'t know what I\'m doing wrong ...

I want to post a json object to a request. But JSONWriter doesn't seem to convert my object, don't know what I'm doing wrong ... here's my code for the conversion..

    customer = [[Customer alloc] init];

Address *tempAddr = [[Address alloc] init];
tempAddr.Line1=strAddr1 ;
tempAddr.Zip =strPost开发者_如何学JAVA;
tempAddr.City =strStreet;
[customer setInvoiceAddress:tempAddr];

customer.FirstName=strFirstName;
customer.LastName=strLastName;
customer.CellPhone=strCellPhone;
customer.Phone=strPhone;
customer.Email=strEmail;

SBJsonWriter *writer = [SBJsonWriter alloc];
NSString *jsonConvertedObj = [writer stringWithObject:customer];
NSLog(@"the json converted object ... %@", jsonConvertedObj);

Please help. I've no idea what's wrong with the code above.


To figure out why your Json parsing fails, You shoud use this approach:

    NSError *error = nil;
    NSString * jsonTest = [[[SBJsonWriter alloc] init] stringWithObject:jsonTestDictionary error:&error];

    if ( ! jsonTest ) {
        NSLog(@"Error: %@", error);
    }else{
        NSLog(@"%@", jsonTest);
    } 

Here is a simple code demonstrating how to use it:

#import <Foundation/Foundation.h>

#import "SBJsonWriter.h"
#import "SBJsonParser.h"


int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSDictionary* aNestedObject = [NSDictionary dictionaryWithObjectsAndKeys:
                                              @"nestedStringValue", @"aStringInNestedObject",
                                              [NSNumber numberWithInt:1], @"aNumberInNestedObject",
                                         nil];

        NSArray * aJSonArray = [[NSArray alloc] initWithObjects: @"arrayItem1", @"arrayItem2", @"arrayItem3", nil];

        NSDictionary * jsonTestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                             @"stringValue", @"aString",
                                             [NSNumber numberWithInt:1], @"aNumber",
                                             [NSNumber numberWithFloat:1.2345f], @"aFloat",
                                             [[NSDate date] description], @"aDate",
                                             aNestedObject, @"nestedObject",
                                             aJSonArray, @"aJSonArray",
                                             nil];

        // create JSON output from dictionary

        NSError *error = nil;
        NSString * jsonTest = [[[SBJsonWriter alloc] init] stringWithObject:jsonTestDictionary error:&error];

        if ( ! jsonTest ) {
            NSLog(@"Error: %@", error);
        }else{
            NSLog(@"%@", jsonTest);
        } 
    }
    return 0;
}

outputs

{
    "aDate":"2012-09-12 07:39:00 +0000",
    "aFloat":1.2345000505447388,
    "nestedObject":{
        "aStringInNestedObject":"nestedStringValue",
        "aNumberInNestedObject":1
     },
    "aJSonList":["arrayItem1","arrayItem2","arrayItem3"],
    "aString":"stringValue",
    "aNumber":1
}

Note:

  1. Using 'error' allowed me to figure out that if you write [NSDate date] instead of [[NSDate date] description] you will get a "JSON serialisation not supported for __NSTaggedDate" error.
  2. notice the float rounding error... 1.2345 became 1.2345000505447388


AFAIK SBJSONWriter only supports conversion of dictionaries and arrays to JSON strings. It won't work for arbitrary objects.


Edit: Here is the corresponding implementation, which returns nil if the supplied object is neither a dictionary nor an array.

- (NSString*)stringWithObject:(id)value {
    if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
        return [self stringWithFragment:value];
    }

    [self clearErrorTrace];
    [self addErrorWithCode:EFRAGMENT description:@"Not valid type for JSON"];
    return nil;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消