如何将AfNetworking响应对象(JSON)映射到自定义类?

sre*_*rgo 4 json ios afnetworking xcode5

我正在使用JSON作为POST方法的响应AFNetworking.我需要将JSON映射到自定义类,并创建一个包含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 = "sreejith@gmail.com";
    headOfficeMobile = "";
    headOfficeName = Koorkenchery;
    headOfficePhone = "";
    id = 0;
    name = "Sathish Clinic";
    ownerAddress = "";
    ownerEmail = "sreejith@gmail.com";
    ownerFirstName = Sathish;
    ownerLastName = Chandran;
    ownerMobile = "";
    ownerPhone = "";
    password = "aW8oFWDMOJUrIV3l7R7hqQ==";
    status = active;
    userName = sathish;
    userType = owner;
};
primary = 1;
retrieveAppointments =     (
);
retrieveDoctorsList =     (
);
retrievePatients =     (
);
retrieveScheduleList =     (
);
success = 1;
user =     (
);    }
Run Code Online (Sandbox Code Playgroud)

自定义类

#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
Run Code Online (Sandbox Code Playgroud)

Mac*_*zko 6

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


die*_*ikh 5

如果您的JSON键与您的自定义类的属性匹配,那么它是直截了当的:

  1. 使用NSJSONSerialization该类将JSON数据反序列化为NSDictionary .
  2. 使用填充自定义对象属性 [object setValuesForKeysWithDictionary:deserializedDictionary]

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

另一种选择是允许自定义对象接受所有类型的键,并通过覆盖在对象内进行映射 -setValue:ForKey: