MJExtension icon indicating copy to clipboard operation
MJExtension copied to clipboard

JSON -> model -> JSON 转换问题

Open SoulArsenic opened this issue 11 years ago • 5 comments

因为服务器数据是前端定义的, 导致现在交互的所有格式都需要用JSON, 但是,因为有的关键字被替换过,导致 model 转JSON的时候 关键字会变成已经替换的key。 不知道我需要在哪做这块的处理呢。

eg:

原始 JSON数据
{
  "id": "2000",
  "box-shaowwidth": "20px"
}


model  中的转换健
+ (NSDictionary *)replacedKeyFromPropertyName{
    return @{
             @"uid":@"id",
             @"box_shaowwidth": @"box-shaowwidth"
             };
}

Model 转换后的 JSON String

{"uid":"2000","box_shaowwidth":"20px"}

SoulArsenic avatar Jul 28 '15 06:07 SoulArsenic

找到了替换的位置, 但是没找到我传进来的那个对照字典在哪存的。 MJProperty 中能看到我自己类型的那个原始的名。 但是获取不到。。。

SoulArsenic avatar Jul 28 '15 08:07 SoulArsenic

给 MJProperty 类加了一个orgName 的属性 ,如果有影射,则使用影射字典中的原始值

.h中
@property (nonatomic, readonly) NSString *orgName;

.m中
-(NSString *)orgName{

    NSString *aString = nil;
    NSArray * pros = self.propertyKeysDict[NSStringFromClass(self.srcClass)];
    MJProperty * pro = [pros firstObject];
    aString = pro.name;
    if (!aString) {
        aString = _name;
    }
   return aString;
}

NSObject+MJKeyValue.m中

将 keyValues[property.name] = value; 替换为 keyValues[property.orgName] = value;

暂时看来 需求满足了, 但是不知道这么做是不是正确的解决办法,求指正

SoulArsenic avatar Jul 28 '15 08:07 SoulArsenic

正确的办法是使用referenceReplacedKeyWhenCreatingKeyValues

xl9211 avatar Aug 20 '15 10:08 xl9211

@LengBinBin 参考@xulin97 的说法

[Model referenceReplacedKeyWhenCreatingKeyValues:YES];

CoderMJLee avatar Aug 20 '15 11:08 CoderMJLee

soga 找到了。THX

SoulArsenic avatar Aug 21 '15 02:08 SoulArsenic