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

我有一个名为“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类中,我正在使用另一个类名“Sign In”,其中包含一些其他属性。

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对象。 所以我使用下面的代码创build字典:

  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,你可以请检查我的代码,让我知道我的错误在哪里。 提前致谢。

如果你正在使用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 ); } 

你应该将你的NSMutableDictionary序列化为JSON。 你可以通过使用NSJSONSerialization来做到这一点:

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

这应该给你你的JSON。

但我没有得到正确的JSON,你可以请检查我的代码,让我知道我的错误在哪里。

问题是你不是在任何地方创build对象的JSON表示; 你只是在创build一个字典。 字典可以转换为JSON(假设它们只包含某些types的数据),但它们本身不是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。

尝试

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