How to include null value in the JSON via NSJSONSerialization?

半世苍凉 提交于 2019-11-30 08:01:24

You have to use NSNull. For instance

Swift

let dict = ["firstKeyHasValue": 2342, "secondKeyHasNoValue": NSNull()]

Objective-C

NSDictionary *dict = @{ @"error": [NSNull null] };

From the official documentation of NSDictionary:

Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.

If you are using Swifty JSON, I've just created a PR that should handle nil. It's not merged yet and might need some improvements. The part that describes how to do that should be a good start to write your own implementation if you need to. The logic is not that complicated but there might be tricky edge cases/performance things to think about.

I know it's not a direct response to the question since it's replacing NSJSONSerialization, but I hope it can help some people frustrated by how Swift handles nil/json!

Ricardo Falasca

Just try something like this:

NSDictionary *jsonObj = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", @"Developer", @"occupation", NULL, @"My NULL field", nil];

and use this object as parameter where you want it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!