I'm setting values for properties of my NSManagedObject, these values are coming from a NSDictionary properly serialized from a JSON file. My problem is, that, when some value is [NSNull null], I can't assign directly to the property:

    fight.winnerID = [dict objectForKey:@"winner"];

this throws a NSInvalidArgumentException

"winnerID"; desired type = NSString; given type = NSNull; value = <null>;

我可以很容易地判断[NSNull null]的值,然后指定nil:

fight.winnerID = [dict objectForKey:@"winner"] == [NSNull null] ? nil : [dict objectForKey:@"winner"];

But I think this is not elegant and gets messy with lots of properties to set.

此外,在处理NSNumber处房产时,这会变得更加困难:

fight.round = [NSNumber numberWithUnsignedInteger:[[dict valueForKey:@"round"] unsignedIntegerValue]]

The NSInvalidArgumentException is now:

[NSNull unsignedIntegerValue]: unrecognized selector sent to instance

In this case I have to treat [dict valueForKey:@"round"] before making an NSUInteger value of it. And the one line solution is gone.

我试着制作一个@try@catch块,但是一旦捕捉到第一个值,它就会跳过整个@try块,并且忽略下一个属性.

有没有更好的方法来处理[NSNull null]个问题,或者让这完全不同但更简单?

推荐答案

如果将其包装在宏中,可能会更容易一些:

#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })

然后你可以写这样的东西

fight.winnerID = NULL_TO_NIL([dict objectForKey:@"winner"]);

Alternatively you can pre-process your dictionary and replace all NSNulls with nil before even trying to stuff it into your managed object.

Json相关问答推荐

Azure数据工厂-WEB活动输出赢得';t返回JSON

Jolt-Json转换:通过引用标识符(而不是索引)设置值

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

Android 如何判断小时时间是否在两个时间之间?

使用不同行数的数据创建嵌套Jolt

jq - 仅在键值对存在的地方打印值

如何在JQ中展平多维数组

jq可以在两个JSON对象列表中依次添加对象吗?

阅读 JSON 正文 Firebase 云函数

如果值不存在,则将值插入 JSON 数组

Qt使用QJsonDocument、QJsonObject、QJsonArray解析JSON

使用 JSONObject 在 Java 中为以下 struct 创建嵌套 JSON 对象?

读取 HttpwebResponse json 响应,C#

jquery用json数据填充下拉列表

如何在java中比较来自JsonObject的空值

在 Django 1.9 中,使用 JSONField(本机 postgres jsonb)的约定是什么?

设置对象不是 JSON 可序列化的

使用新的 Net Core 3.0 Json 时忽略属性

如何对 Javascript 对象进行排序,或将其转换为数组?

如何在本地存储中存储对象数组?