从JSON序列化中在NSUserDefaults中存储[NSNull null]值会导致不必要的异常 [英] storing [NSNull null] values in NSUserDefaults, from JSON serialization, causes unwanted exceptions
问题描述
我有一个应用程序,我使用基于JSON的API。作为JSON的一部分,通常将值设置为null。这可能很常见:
I've got an app where I use a JSON based API. As part of JSON, often values are set to "null". This may be common:
{"data":["one","two","three"],"name":null,otherstuff:10}
最近我试图存储一个misc NSDictionary层次结构,已转换来自NSSserDefaults中的JSON对象。不幸的是,如果存在空数据,则会导致异常,在IOS中转换为[NSNull null]。显然,无法保存在prefs中。
Recently I've tried to store a misc NSDictionary hierarchy, converted from a JSON object, in NSUserDefaults. Unfortunately it causes an exception if there is null data, converted in IOS to [NSNull null]. Apparently that can't be saved in prefs.
我想知道是否有人曾经解决过这个问题?我尝试添加一些逻辑来首先从JSON中删除所有空值,但成功有限,但在存储之前必须修改数据似乎是不合适的。有没有更好的方法来处理这个问题?
I was wondering if anyone has worked around this before? I tried to add some logic to remove all null values from the JSON first, with limited success, but it seems inappropriate to have to modify the data before storing it. Is there a better way to handle this?
推荐答案
我尝试了一些递归解决方案,但它们往往很复杂而且不是t处理好混合型内容。在最简单的层面上,这是一个平坦的例子,如果你有一个可预测的,平坦的清洁响应,那么效果很好。
I've tried some recursive solutions but they tend to be complicated and don't handle mixed type content well. At the simplest level here is a flat example that works well if you have a predictable, flat response to clean.
NSMutableDictionary *dictMutable = [dict mutableCopy];
[dictMutable removeObjectsForKeys:[dict allKeysForObject:[NSNull null]]];
这篇关于从JSON序列化中在NSUserDefaults中存储[NSNull null]值会导致不必要的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!