【问题标题】:How to map AfNetworking response object (JSON) to custom class?如何将 AfNetworking 响应对象 (JSON) 映射到自定义类?
【发布时间】:2014-03-04 14:32:03
【问题描述】:

我收到一个 JSON 作为对使用 AFNetworkingPOST 方法的响应。 我需要将 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 =     (
);    }

自定义类

#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

【问题讨论】:

    标签: ios json xcode5 afnetworking


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您的 JSON 键与您的自定义类的属性相匹配,那么这很简单:

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

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

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

      【讨论】:

        【解决方案3】:

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

        如果你想自己处理

        {} : Represents object/Dictionary
        [] : Represents array
        

        深入写下每一个细节并得到你需要的东西

        【讨论】:

          猜你喜欢
          • 2014-01-21
          • 1970-01-01
          • 1970-01-01
          • 2018-08-20
          • 2020-09-13
          • 2013-06-16
          • 2017-12-24
          • 2015-06-27
          • 1970-01-01
          相关资源
          最近更新 更多