赞
踩
本文翻译自:Representing null in JSON
What is the preferred method for returning null values in JSON? 在JSON中返回空值的首选方法是什么? Is there a different preference for primitives? 原语是否有不同的偏好?
For example, if my object on the server has an Integer called "myCount" with no value, the most correct JSON for that value would be: 例如,如果服务器上的对象有一个名为“myCount”且没有值的Integer,那么该值的最正确的JSON将是:
{}
or 要么
- {
- "myCount": null
- }
or 要么
- {
- "myCount": 0
- }
Same question for Strings - if I have a null string "myString" on the server, is the best JSON: 字符串的相同问题 - 如果我在服务器上有一个空字符串“myString”,则是最好的JSON:
{}
or 要么
- {
- "myString": null
- }
or 要么
- {
- "myString": ""
- }
or (lord help me) 或者(上帝帮助我)
- {
- "myString": "null"
- }
I like the convention for collections to be represented in the JSON as an empty collection http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html 我喜欢集合的约定在JSON中表示为空集合http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html
An empty Array would be represented: 将显示一个空数组:
- {
- "myArray": []
- }
EDIT Summary 编辑摘要
The 'personal preference' argument seems realistic, but short sighted in that, as a community we will be consuming an ever greater number of disparate services/sources. “个人偏好”的观点似乎是现实的,但短视的是,作为一个社区,我们将消耗更多不同的服务/来源。 Conventions for JSON structure would help normalize consumption and reuse of said services. JSON结构的约定将有助于规范化所述服务的消耗和重用。 As far as establishing a standard, I would suggest adopting most of the Jackson conventions with a few exceptions: 就建立标准而言,我建议采用大多数杰克逊公约,但有一些例外:
If you are returning a JSON object with mostly null values, you may have a candidate for refactoring into multiple services. 如果要返回一个主要为空值的JSON对象,则可能有一个候选者可以重构为多个服务。
- {
-
- "value1": null,
-
- "value2": null,
-
- "text1": null,
-
- "text2": "hello",
-
- "intValue": 0, //use primitive only if you are absolutely sure the answer is 0
-
- "myList": [],
-
- "myEmptyList": null, //NOT BEST PRACTICE - return [] instead
-
- "boolean1": null, //use primitive only if you are absolutely sure the answer is true/false
-
- "littleboolean": false
-
- }
The above JSON was generated from the following Java class. 上面的JSON是从以下Java类生成的。
- package jackson;
-
- import java.util.ArrayList;
- import java.util.List;
-
- import com.fasterxml.jackson.databind.ObjectMapper;
-
- public class JacksonApp {
-
- public static class Data {
-
- public Integer value1;
-
- public Integer value2;
-
- public String text1;
-
- public String text2 = "hello";
-
- public int intValue;
-
- public List<Object> myList = new ArrayList<Object>();
-
- public List<Object> myEmptyList;
-
- public Boolean boolean1;
-
- public boolean littleboolean;
-
- }
-
- public static void main(String[] args) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- System.out.println(mapper.writeValueAsString(new Data()));
- }
- }
Maven dependency: Maven依赖:
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.3.0</version>
- </dependency>
参考:https://stackoom.com/question/1QcXH/在JSON中表示null
I would pick "default" for data type of variable ( null
for strings/objects, 0
for numbers), but indeed check what code that will consume the object expects. 我会为变量的数据类型选择“default”(字符串/对象为null
,数字为0
),但确实检查将使用对象所需的代码。 Don't forget there there is sometimes distinction between null
/default vs. "not present". 不要忘记, null
/ default与“not present”之间有时会有区别。
Check out null object pattern - sometimes it is better to pass some special object instead of null
(ie []
array instead of null
for arrays or ""
for strings). 检查空对象模式 - 有时最好传递一些特殊对象而不是null
(即[]
数组而不是数组的null
或字符串的""
)。
This is a personal and situational choice. 这是个人和情境选择。 The important thing to remember is that the empty string and the number zero are conceptually distinct from null
. 要记住的重要一点是,空字符串和数字零在概念上与null
不同。
In the case of a count
you probably always want some valid number (unless the count
is unknown or undefined), but in the case of strings, who knows? 在count
的情况下,您可能总是想要一些有效数字(除非count
未知或未定义),但在字符串的情况下,谁知道? The empty string could mean something in your application. 空字符串可能意味着您的应用程序。 Or maybe it doesn't. 或者它可能没有。 That's up to you to decide. 这取决于你自己决定。
I would use null
to show that there is no value for that particular key. 我会使用null
来表明该特定键没有值。 For example, use null
to represent that "number of devices in your household connects to internet" is unknown. 例如,使用null
表示“您家中的设备连接到互联网的数量”未知。
On the other hand, use {}
if that particular key is not applicable. 另一方面,如果该特定键不适用,请使用{}
。 For example, you should not show a count, even if null
, to the question "number of cars that has active internet connection" is asked to someone who does not own any cars. 例如,您不应该向没有任何车辆的人询问“具有活动互联网连接的汽车数量”这一问题,即使是null
。
I would avoid defaulting any value unless that default makes sense. 除非默认有意义,否则我会避免违约。 While you may decide to use null
to represent no value, certainly never use "null"
to do so. 虽然您可能决定使用null
来表示没有值,但肯定不会使用"null"
来表示。
Let's evaluate the parsing of each: 让我们评估每个解析:
http://jsfiddle.net/brandonscript/Y2dGv/ http://jsfiddle.net/brandonscript/Y2dGv/
- var json1 = '{}';
- var json2 = '{"myCount": null}';
- var json3 = '{"myCount": 0}';
- var json4 = '{"myString": ""}';
- var json5 = '{"myString": "null"}';
- var json6 = '{"myArray": []}';
-
- console.log(JSON.parse(json1)); // {}
- console.log(JSON.parse(json2)); // {myCount: null}
- console.log(JSON.parse(json3)); // {myCount: 0}
- console.log(JSON.parse(json4)); // {myString: ""}
- console.log(JSON.parse(json5)); // {myString: "null"}
- console.log(JSON.parse(json6)); // {myArray: []}
The tl;dr here: tl;博士在这里:
The fragment in the json2 variable is the way the JSON spec indicates
null
should be represented. json2变量中的片段是JSON规范指示应该表示null
的方式。 But as always, it depends on what you're doing -- sometimes the "right" way to do it doesn't always work for your situation. 但与往常一样,这取决于你正在做什么 - 有时候“正确”的做法并不总是适合你的情况。 Use your judgement and make an informed decision. 用你的判断做出明智的决定。
JSON1 {}
JSON1 {}
This returns an empty object. 这将返回一个空对象。 There is no data there, and it's only going to tell you that whatever key you're looking for (be it myCount
or something else) is of type undefined
. 那里没有数据,而且它只会告诉你,你正在寻找的任何键(无论是myCount
还是其他)都是undefined
类型。
JSON2 {"myCount": null}
JSON2 {"myCount": null}
In this case, myCount
is actually defined, albeit its value is null
. 在这种情况下, myCount
实际上已定义,尽管其值为null
。 This is not the same as both "not undefined
and not null
", and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail. 这是不一样的两个“不undefined
和不null
”,如果你是一个条件或其他测试,这可能会成功,而JSON1会失败。
This is the definitive way to represent null
per the JSON spec . 这是根据JSON规范表示null
的明确方法。
JSON3 {"myCount": 0}
JSON3 {"myCount": 0}
In this case, myCount is 0. That's not the same as null
, and it's not the same as false
. 在这种情况下,myCount为0.这与null
,并且它与false
。 If your conditional statement evaluates myCount > 0
, then this might be worthwhile to have. 如果条件语句评估myCount > 0
,那么这可能是值得的。 Moreover, if you're running calculations based on the value here, 0 could be useful. 此外,如果您根据此处的值运行计算,则0可能很有用。 If you're trying to test for null
however, this is actually not going to work at all. 但是,如果您尝试测试null
,则实际上根本不起作用。
JSON4 {"myString": ""}
JSON4 {"myString": ""}
In this case, you're getting an empty string. 在这种情况下,您将获得一个空字符串。 Again, as with JSON2, it's defined, but it's empty. 同样,与JSON2一样,它已定义,但它是空的。 You could test for if (obj.myString == "")
but you could not test for null
or undefined
. 您可以测试if (obj.myString == "")
但无法测试null
或undefined
。
JSON5 {"myString": "null"}
JSON5 {"myString": "null"}
This is probably going to get you in trouble, because you're setting the string value to null; 这可能会让你遇到麻烦,因为你将字符串值设置为null; in this case, obj.myString == "null"
however it is not == null
. 在这种情况下, obj.myString == "null"
但它不是 == null
。
JSON6 {"myArray": []}
JSON6 {"myArray": []}
This will tell you that your array myArray
exists, but it's empty. 这将告诉您数组myArray
存在,但它是空的。 This is useful if you're trying to perform a count or evaluation on myArray
. 如果您尝试对myArray
执行计数或评估,这非常有用。 For instance, say you wanted to evaluate the number of photos a user posted - you could do myArray.length
and it would return 0
: defined, but no photos posted. 例如,假设您想评估用户发布的照片数量 - 您可以执行myArray.length
并返回0
:已定义,但未发布照片。
null
is not zero. null
不为零。 It is not a value, per se : it is a value outside the domain of the variable indicating missing or unknown data. 这不是一个值本身 :它是变量,指示丢失的或未知的数据的域之外的值。
There is only one way to represent null
in JSON. 在JSON中只有一种表示null
方法。 Per the specs ( RFC 4627 and json.org ): 根据规范( RFC 4627和json.org ):
2.1. 2.1。 Values 值\n\nA JSON value MUST be an object, array, number, or string, or one of JSON值必须是对象,数组,数字或字符串,或者是其中之一\nthe following three literal names: 以下三个字面名称:\n\n false null true false null true\n
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。