当前位置:   article > 正文

在JSON中表示null_json null

json null

本文翻译自: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 要么

  1. {
  2. "myCount": null
  3. }

or 要么

  1. {
  2. "myCount": 0
  3. }

Same question for Strings - if I have a null string "myString" on the server, is the best JSON: 字符串的相同问题 - 如果我在服务器上有一个空字符串“myString”,则是最好的JSON:

{}

or 要么

  1. {
  2. "myString": null
  3. }

or 要么

  1. {
  2. "myString": ""
  3. }

or (lord help me) 或者(上帝帮助我)

  1. {
  2. "myString": "null"
  3. }

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: 将显示一个空数组:

  1. {
  2. "myArray": []
  3. }

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: 就建立标准而言,我建议采用大多数杰克逊公约,但有一些例外:

  • Objects are preferred over primitives. 对象比基元更受欢迎。
  • Empty collections are preferred over null. 空集合优先于null。
  • Objects with no value are represented as null. 没有值的对象表示为null。
  • Primitives return their value. 基元返回它们的价值。

If you are returning a JSON object with mostly null values, you may have a candidate for refactoring into multiple services. 如果要返回一个主要为空值的JSON对象,则可能有一个候选者可以重构为多个服务。

  1. {
  2. "value1": null,
  3. "value2": null,
  4. "text1": null,
  5. "text2": "hello",
  6. "intValue": 0, //use primitive only if you are absolutely sure the answer is 0
  7. "myList": [],
  8. "myEmptyList": null, //NOT BEST PRACTICE - return [] instead
  9. "boolean1": null, //use primitive only if you are absolutely sure the answer is true/false
  10. "littleboolean": false
  11. }

The above JSON was generated from the following Java class. 上面的JSON是从以下Java类生成的。

  1. package jackson;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. public class JacksonApp {
  6. public static class Data {
  7. public Integer value1;
  8. public Integer value2;
  9. public String text1;
  10. public String text2 = "hello";
  11. public int intValue;
  12. public List<Object> myList = new ArrayList<Object>();
  13. public List<Object> myEmptyList;
  14. public Boolean boolean1;
  15. public boolean littleboolean;
  16. }
  17. public static void main(String[] args) throws Exception {
  18. ObjectMapper mapper = new ObjectMapper();
  19. System.out.println(mapper.writeValueAsString(new Data()));
  20. }
  21. }

Maven dependency: Maven依赖:

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-core</artifactId>
  4. <version>2.3.0</version>
  5. </dependency>

#1楼

参考:https://stackoom.com/question/1QcXH/在JSON中表示null


#2楼

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或字符串的"" )。


#3楼

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. 这取决于你自己决定。


#4楼

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"来表示。


#5楼

Let's evaluate the parsing of each: 让我们评估每个解析:

http://jsfiddle.net/brandonscript/Y2dGv/ http://jsfiddle.net/brandonscript/Y2dGv/

  1. var json1 = '{}';
  2. var json2 = '{"myCount": null}';
  3. var json3 = '{"myCount": 0}';
  4. var json4 = '{"myString": ""}';
  5. var json5 = '{"myString": "null"}';
  6. var json6 = '{"myArray": []}';
  7. console.log(JSON.parse(json1)); // {}
  8. console.log(JSON.parse(json2)); // {myCount: null}
  9. console.log(JSON.parse(json3)); // {myCount: 0}
  10. console.log(JSON.parse(json4)); // {myString: ""}
  11. console.log(JSON.parse(json5)); // {myString: "null"}
  12. 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 == "")但无法测试nullundefined


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 :已定义,但未发布照片。


#6楼

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 4627json.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 tr​​ue\n

在此输入图像描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/485455
推荐阅读
相关标签
  

闽ICP备14008679号