在 JSON 中表示 null [英] Representing null in JSON

查看:41
本文介绍了在 JSON 中表示 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JSON 中返回空值的首选方法是什么?对原语有不同的偏好吗?

例如,如果我在服务器上的对象有一个名为myCount"的整数,没有值,该值最正确的 JSON 是:

{}

{myCount":空}

{我的计数":0}

字符串的相同问题 - 如果我有一个空字符串myString";在服务器上,是最好的 JSON:

{}

{myString":空}

{我的字符串":"}

或(大神帮帮我)

{myString":null"}

我喜欢将集合在 JSON 中表示为空集合的约定 http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

将表示一个空数组:

{我的数组":[]}

编辑摘要

个人偏好"论点似乎很现实,但在这一点上是短视的,作为一个社区,我们将消耗越来越多的不同服务/来源.JSON 结构的约定将有助于规范所述服务的使用和重用.就建立标准而言,我建议采用大部分 Jackson 约定,但有一些例外:

  • 对象优于基元.
  • 空集合优于空集合.
  • 没有值的对象表示为空.
  • 原语返回它们的值.

如果您返回的 JSON 对象大部分为空值,则您可能需要重构为多个服务.

{值1":空,值2":空,text1":空,text2":你好",intValue": 0,//仅当您绝对确定答案为 0 时才使用原语我的列表":[],myEmptyList":null,//不是最佳实践 - 改为返回 []boolean1": null,//仅当您绝对确定答案为真/假时才使用原语小布尔":假}

以上 JSON 是从以下 Java 类生成的.

package jackson;导入 java.util.ArrayList;导入 java.util.List;导入 com.fasterxml.jackson.databind.ObjectMapper;公共类 JacksonApp {公共静态类数据{公共整数值1;公共整数值2;公共字符串 text1;public String text2 =你好";公共 int 值;公共列表<对象>myList = new ArrayList();公共列表<对象>myEmptyList;公共布尔布尔值1;public boolean littleboolean;}public static void main(String[] args) 抛出异常 {ObjectMapper mapper = new ObjectMapper();System.out.println(mapper.writeValueAsString(new Data()));}}

Maven 依赖:

<groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.3.0</version></依赖>

解决方案

让我们评估每个的解析:

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}控制台.log(JSON.parse(json3));//{我的计数:0}console.log(JSON.parse(json4));//{myString: ""}控制台.log(JSON.parse(json5));//{myString: "null"}console.log(JSON.parse(json6));//{myArray: []}


<块引用>

tl;dr 在这里:

json2 变量中的片段是JSON 规范 表示null 应该被表示.但与往常一样,这取决于你在做什么——有时是正确的".这样做的方法并不总是适合您的情况.运用您的判断力并做出明智的决定.


JSON1 {}

这将返回一个空对象.那里没有数据,它只会告诉您您正在寻找的任何键(无论是 myCount 还是其他东西)都是 undefined 类型.


JSON2 {myCount": null}

在这种情况下,myCount 实际上是定义的,尽管它的值为 null.这与not undefined 和 not null"不同,如果您正在测试一种或另一种情况,这可能会成功,而 JSON1 会失败.

这是根据 JSON 规范表示 null 的权威方式.


JSON3 {myCount": 0}

在这种情况下,myCount 为 0.这与 null 不同,也与 false 不同.如果您的条件语句计算 myCount >0,那么这可能值得拥有.此外,如果您根据此处的值运行计算,则 0 可能很有用.但是,如果您尝试测试 null,这实际上根本不起作用.


JSON4 {"myString":""}

在这种情况下,您得到的是一个空字符串.同样,与 JSON2 一样,它已定义,但它是空的.您可以测试 if (obj.myString == "") 但无法测试 nullundefined.


JSON5 {myString": null"}

这可能会给您带来麻烦,因为您将 string 值设置为 null;在这种情况下,obj.myString == "null" 但是它not == null.


JSON6 {myArray": []}

这会告诉你你的数组 myArray 存在,但它是空的.如果您尝试对 myArray 执行计数或评估,这将非常有用.例如,假设您想评估用户发布的照片​​数量 - 您可以执行 myArray.length 并且它会返回 0: 已定义,但没有发布照片.

What is the preferred method for returning null values in 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:

{}

or

{
    "myCount": null
}

or

{
    "myCount": 0
}

Same question for Strings - if I have a null string "myString" on the server, is the best 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

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. 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.
  • Objects with no value are represented as 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.

{
    "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.

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:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.3.0</version>
</dependency>

解决方案

Let's evaluate the parsing of each:

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:

The fragment in the json2 variable is the way the JSON spec indicates null should be represented. 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 {}

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.


JSON2 {"myCount": null}

In this case, myCount is actually defined, albeit its value is 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.

This is the definitive way to represent null per the JSON spec.


JSON3 {"myCount": 0}

In this case, myCount is 0. That's not the same as null, and it's not the same as false. If your conditional statement evaluates myCount > 0, then this might be worthwhile to have. Moreover, if you're running calculations based on the value here, 0 could be useful. If you're trying to test for null however, this is actually not going to work at all.


JSON4 {"myString": ""}

In this case, you're getting an empty string. Again, as with JSON2, it's defined, but it's empty. You could test for if (obj.myString == "") but you could not test for null or undefined.


JSON5 {"myString": "null"}

This is probably going to get you in trouble, because you're setting the string value to null; in this case, obj.myString == "null" however it is not == null.


JSON6 {"myArray": []}

This will tell you that your array myArray exists, but it's empty. This is useful if you're trying to perform a count or evaluation on 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.

这篇关于在 JSON 中表示 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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