我想将数组序列化为 JSON。这是我的 JSON -
{
"User":{"Id":"1222","Email":"asdad@adasd.com"},
"Person":{"Name":"John","Surname":"Smith"}
}
值 1222、asdad@adasd.com、John、Smith 是示例。此值将在控制器中定义。
我不知道如何在 JSON 中处理序列化这个数组。我需要将对象 - 用户和人员发送到具有不同值的服务器,具体取决于用户。这是我的模型。两者都是数组。
这是我的代码
标题
#import <Foundation/Foundation.h>
#import "BaseRequest.h"
@interface SaveUserProfileRequest : BaseRequest {
NSMutableArray *_user;
NSMutableArray *_person;
NSMutableArray *_address;
NSString *_userId;
NSString *_userEmail;
NSString *_userName;
NSString *_userSurname;
}
- (id)initWithUser:(NSMutableArray*)user andPerson:(NSMutableArray*)person andAddress:(NSMutableArray*)address andUserId:(NSString*)userId andUserEmail:(NSString*)userEmail andUserName:(NSString*)userName andUserSurname:(NSString*)userSurname;
@property (nonatomic, strong) NSMutableArray* user;
@property (nonatomic, strong) NSMutableArray* person;
@property (nonatomic, strong) NSMutableArray* address;
@property (nonatomic, strong) NSString* userId;
@property (nonatomic, strong) NSString* userEmail;
@property (nonatomic, strong) NSString* userName;
@property (nonatomic, strong) NSString* userSurname;
@end
执行
#import "SaveUserProfileRequest.h"
#import "SaveUserProfileResponse.h"
#import "OrderedDictionary.h"
#import "BaseData.h"
@implementation SaveUserProfileRequest
@synthesize user=_user, person=_person, address=_address, userId=_userId, userEmail=_userEmail, userName=_userName, userSurname=_userSurname;
- (id)initWithUser:(NSMutableArray*)user andPerson:(NSMutableArray*)person andAddress:(NSMutableArray*)address andUserId:(NSString*)userId andUserEmail:(NSString*)userEmail andUserName:(NSString*)userName andUserSurname:(NSString*)userSurname; {
self = [super init];
if(self){
self.user = user;
self.person = person;
self.address = address;
self.userId = userId;
self.userEmail = userEmail;
self.userName = userName;
self.userSurname = userSurname;
}
return self;
}
- (NSDictionary*) serialize{
OrderedDictionary *sup = [OrderedDictionary dictionaryWithCapacity:3];
[sup setValue:self.user forKey:@"User"];
[sup setValue:self.person forKey:@"Person"];
NSArray *users = [OrderedDictionary valueForKey:@"User"];
_user = [NSMutableArray arrayWithCapacity:[users count]];
for(NSDictionary *user in users){
OrderedDictionary *userDict = [OrderedDictionary dictionaryWithCapacity:2];
[userDict setValue:self.userId forKey:@"Id"];
[userDict setValue:self.userEmail forKey:@"Mail"];
return userDict;
}
NSArray *persons = [OrderedDictionary valueForKey:@"Person"];
_person = [NSMutableArray arrayWithCapacity:[persons count]];
for(NSDictionary *person in persons){
OrderedDictionary *personsDict = [OrderedDictionary dictionaryWithCapacity:2];
[personsDict setValue:self.userName forKey:@"Name"];
[personsDict setValue:self.userSurname forKey:@"Surname"];
return personsDict;
}
return sup;
}
请帮帮我每一个小提示都会非常感激。谢谢 !