问题:在iOS中将对象转换为json

时间:2013-12-12 12:35:05

标签: ios objective-c json nsmutabledictionary

我有一个名为“Store”的主要实体类,如:

Store.h: -

#import <Foundation/Foundation.h>
#import "SignIn.h"

@interface Store : NSObject

@property (nonatomic, retain) NSString *storeId;
@property (nonatomic, retain) NSString *storeProfileId;
@property (nonatomic, retain) NSString *storeName;
@property (nonatomic, retain) NSString *storeRegion;

@property (nonatomic, retain) SignIn *signIn;

@end

Store.m: -

#import "Store.h"

@implementation Store

@synthesize storeId, storeProfileId, storeName, storeRegion, signIn;

- (id) initWithCoder: (NSCoder *)coder
{
    self = [[Store alloc] init];
    if (self != nil)
    {
        self.storeId = [coder decodeObjectForKey:@"storeId"];
        self.storeProfileId = [coder decodeObjectForKey:@"storeProfileId"];
        self.storeName = [coder decodeObjectForKey:@"storeName"];
        self.storeRegion = [coder decodeObjectForKey:@"storeRegion"];

        self.signIn = [coder decodeObjectForKey:@"signIn"];
    }
    return self;
}

- (void)encodeWithCoder: (NSCoder *)coder
{
    [coder encodeObject:storeId forKey:@"storeId"];
    [coder encodeObject:storeProfileId forKey:@"storeProfileId"];
    [coder encodeObject:storeName forKey:@"storeName"];
    [coder encodeObject:storeRegion forKey:@"storeRegion"];

    [coder encodeObject:signIn forKey:@"signIn"];
}

@end

在Store类中,我还有一个类名“登录”,其中包含一些其他属性。

SignIn.h: -

#import <Foundation/Foundation.h>

@interface SignIn : NSObject

@property (nonatomic, retain) NSString *inTime;
@property (nonatomic, retain) NSString *outTime;
@property (nonatomic, retain) NSString *isStatus;

@end

SignIn.m: -

#import "SignIn.h"

@implementation SignIn
@synthesize inTime, outTime, isStatus;

- (id) initWithCoder: (NSCoder *)coder
{
    self = [[SignIn alloc] init];
    if (self != nil)
    {
        self.inTime = [coder decodeObjectForKey:@"inTime"];
        self.outTime = [coder decodeObjectForKey:@"outTime"];
        self.isStatus = [coder decodeObjectForKey:@"isStatus"];
    }
    return self;
}

- (void)encodeWithCoder: (NSCoder *)coder
{
    [coder encodeObject:inTime forKey:@"inTime"];
    [coder encodeObject:outTime forKey:@"outTime"];
    [coder encodeObject:isStatus forKey:@"isStatus"];
}

@end

现在我需要在服务器上发布此Store对象。所以我使用下面的代码创建字典:

  NSMutableArray *storeJSONArray=[NSMutableArray array];
    for (Store *store in array1) {

        NSMutableDictionary *storeJSON=[NSMutableDictionary dictionary];

        [storeJSON setValue:store.storeId forKey:@"storeId"];
        [storeJSON setValue:store.storeProfileId forKey:@"storeProfileId"];
        [storeJSON setValue:store.storeName forKey:@"storeName"];
        [storeJSON setValue:store.storeRegion forKey:@"storeRegion"];


        //Sign In
        [storeJSON setValue:store.signIn.inTime forKey:@"inTime"];
        [storeJSON setValue:store.signIn.outTime forKey:@"outTime"];
        [storeJSON setValue:store.signIn.isStatus forKey:@"isStatus"];

        [storeJSONArray addObject:storeJSON];
    }

    NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
    [dictionnary setObject:storeJSONArray forKey:@"StoreRequest"];

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
                                                       options:kNilOptions
                                                         error:&error];

    NSString *urlString =@"http://...................php";

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:jsonData];
    NSURLResponse *response = NULL;
    NSError *requestError = NULL;

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;

但是我没有得到正确的JSON,请你查一下我的代码并让我知道我的错误在哪里。在此先感谢。

4 个答案:

答案 0 :(得分:1)

  

但是我没有得到正确的JSON,请你查一下我的代码并让我知道我的错误在哪里。

问题是你没有在任何地方创建对象的JSON表示;你只是在创建一本字典。字典可以转换为JSON(前提是它们只包含某些类型的数据),但它们本身不是JSON - 它们是Objective-C对象。您可能希望添加如下调用:

NSError *error = nil;
NSData *json = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];

您已经向我们展示了两个类中的NSCoding方法,但您应该了解NSJSONSerialization不依赖于NSCoding,因此这些代码都不会发挥作用。

更新:修改您的示例以包含NSJSONSerialization后,您说您正在获得如下所示的JSON:

{"StoreRequest":[{"signOutStatus":false,"greetingStatus":false,"isBackFromVisit"‌​‌​:false,"digitalMerchandisingStatus":false,"feedbackStatus":false,"storeRegion":‌​"B‌​ishan Junction 8","isSubmit":false,"storeName":"Best Denki","storeId":"SG-2","planVisitStatus":false,"storeProfileId":5,"merchandisin‌​‌​gStatus":false}]}

考虑到您添加到dictionnary的值,这似乎是正确的。但是你说你想要的是:

{ "Checklist": [ { "vm_code": "SGVM0001", "store_id": "SG-12", "store_name": "Best Denki", "store_address": "Ngee Ann City", "visit_date": { "date": "2013-12-04 00:00:00", "timezone_type": 3, "timezone": "Asia/Calcutta" } "sign_in": { "date": "2013-12-05 11:03:00", "timezone_type": 3, "timezone": "Asia/Calcutta" }]

这与您传递给NSJSONSerialization的对象完全不匹配。所以,这里的问题是你向NSJSONSerialization提供了错误的数据。

答案 1 :(得分:1)

如果您使用的是iOS 5+,则可以使用NSJSONSerialization

NSData *data= [NSJSONSerialization dataWithJSONObject:storeJSONArray 
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:nil];
if (data)
{
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"JSON : %@",json );
}

答案 2 :(得分:1)

您应该将NSMutableDictionary序列化为JSON。 您可以使用NSJSONSerialization执行此操作:

NSError *error;
NSData *myData = [NSJSONSerialization dataWithJSONObject:storeJSON options:0 error:&error];
NSString *myJSON = [[NSString alloc] initWithBytes:[myData bytes]];

这应该会给你你的JSON。

答案 3 :(得分:0)

尝试

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput 
                                                   options:kNilOptions // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}