在 NSUserDefaults 中存储 [NSNull null] 值,来自 JSON 序列化,导致不需要的异常 [英] storing [NSNull null] values in NSUserDefaults, from JSON serialization, causes unwanted exceptions

查看:30
本文介绍了在 NSUserDefaults 中存储 [NSNull null] 值,来自 JSON 序列化,导致不需要的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我使用基于 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}

最近我尝试在 NSUserDefaults 中存储从 JSON 对象转换而来的杂项 NSDictionary 层次结构.不幸的是,如果有空数据,它会导致异常,在 IOS 中转换为 [NSNull null].显然这不能保存在首选项中.

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?

推荐答案

我尝试了一些递归解决方案,但它们往往很复杂,并且不能很好地处理混合类型的内容.在最简单的层面上,这里是一个平面示例,如果您对清洁有可预测的平面响应,则效果很好.

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]]];

这篇关于在 NSUserDefaults 中存储 [NSNull null] 值,来自 JSON 序列化,导致不需要的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆