2014-02-07 219 views
4

我收到JSON作为回应POST方法使用AFNetworking。 我需要将JSON映射到自定义类,并创建一个包含JSON中值的对象。如何将AfNetworking响应对象(JSON)映射到自定义类?

JSON字符串

{ 
branch =  { 
    address = ""; 
    email = ""; 
    globalId = 174; 
    id = 0; 
    mobile = 9846147442; 
    name = "Sathish Clininc Branch1"; 
    netMdId = 132; 
    numberOfDevices = 0; 
    organisationName = "<null>"; 
    passPhrase =   (
    ); 
    phone = 04872279166; 
    status = active; 
}; 
error = "<null>"; 
netmd =  { 
    globalId = 132; 
    headOfficeAddress = ""; 
    headOfficeEmail = "[email protected]"; 
    headOfficeMobile = ""; 
    headOfficeName = Koorkenchery; 
    headOfficePhone = ""; 
    id = 0; 
    name = "Sathish Clinic"; 
    ownerAddress = ""; 
    ownerEmail = "[email protected]"; 
    ownerFirstName = Sathish; 
    ownerLastName = Chandran; 
    ownerMobile = ""; 
    ownerPhone = ""; 
    password = "aW8oFWDMOJUrIV3l7R7hqQ=="; 
    status = active; 
    userName = sathish; 
    userType = owner; 
}; 
primary = 1; 
retrieveAppointments =  (
); 
retrieveDoctorsList =  (
); 
retrievePatients =  (
); 
retrieveScheduleList =  (
); 
success = 1; 
user =  (
); } 

自定义类

#import <Foundation/Foundation.h> 
#import "ErrorDTO.h" 
#import "NetMdBranchDTO.h" 
#import "NetMdDTO.h" 
@interface NetMdActivationResponseDTO : NSObject 
@property (nonatomic, strong)ErrorDTO* error; 
@property (nonatomic, assign) BOOL success; 
@property (nonatomic, strong) NetMdBranchDTO* branch; 
@property (nonatomic, strong) NetMdDTO* netmd; 
@property (nonatomic, strong) NSArray* user; 
@property (nonatomic, strong) NSArray* retrieveDoctorsList; 
@property (nonatomic, strong) NSArray* retrievePatients; 
@property (nonatomic, strong) NSArray* retrieveScheduleList; 
@property (nonatomic, strong) NSArray* retrieveAppointments; 
@property (nonatomic, assign) BOOL primary; 

@end 

回答

1

使用JSON Accelerator生成你的类添加到代码中执行

如果你想自己

对付它
{} : Represents object/Dictionary 
[] : Represents array 

潜水在写每一个钻下来,得到你需要

4

如果你的JSON钥匙匹配您的自定义类的属性则是直截了当:

  1. 使用反序列化JSON数据到一个NSDictionary NSJSONSerialization类。
  2. 填写您的自定义使用[object setValuesForKeysWithDictionary:deserializedDictionary]

如果密钥不匹配不是设置属性,如object.user = deserializedDictionary[@"userName"]

另一种选择是允许自定义对象接受各种按键和做内的映射对象的属性被覆盖的对象-setValue:ForKey:

6

您可以使用Mantle提升您的价值对象。维护所有转换将更容易。