如何通过NSJSONSerialization在JSON中包含空值? [英] How to include null value in the JSON via NSJSONSerialization?

查看:458
本文介绍了如何通过NSJSONSerialization在JSON中包含空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我知道如何使用NSJSONSerialization。我正在进行的调用是:

I think I get it how to use the NSJSONSerialization over all. The call I am making is:

[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]

其中 parameters 是一个NSDictionary,其中包含要在JSON请求中使用的键和值。一切都很好,直到我必须使用 null 作为值而不是空字符串。我找不到将值设置为 null 的方法。我需要创建的 json 示例是:

where parameters is a NSDictionary which includes keys and values to use in the JSON request. Everything is fine and all, until I have to use null as a value instead of an empty string. I can't find a way to set the value as null at all. The example of json that I need to create is:

{"target"
  {"firstname":<firstname>,
   "lastname":<lastname>},
 "error":null
}

服务器的设置方式是,如果没有错误,它可能会出现错误,或者 null

The way server is setup is that it's expecting either an error as a string or a null if there's no error.

任何想法?我错过了API调用或类似的东西吗?

Any ideas? Am I missing an API call or something like that?

谢谢!

推荐答案

您必须使用 NSNull 。例如

Swift

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

目标-C

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

来自NSDictionary


密钥和值都不能为零;如果你需要在字典中表示空值,你应该使用NSNull。

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

这篇关于如何通过NSJSONSerialization在JSON中包含空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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