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

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

问题描述

在JSON中返回空值的首选方法是什么?例如,如果服务器上的对象具有一个名为myCount的Integer而没有值,则该值的最正确的JSON将是:

  {} 

  {
myCount:null
}

  {
myCount:0
}

- 如果服务器上有空字符串myString,是最好的JSON: / code>

  { 
myString:null
}

  {
myStrung:
}

或(lord help me)

  {
myString :null
}

我喜欢在JSON作为一个空集合 http://jtechies.blogspot.nl/2012/ 07 / item-43-return-empty-arrays-or.html



一个空数组将被表示:

  {
myArray:[]
}

编辑总结

'个人偏好'的说法似乎很现实,一个社区将消耗更多不同的服务/来源。 JSON结构的惯例将有助于规范化所述服务的消耗和重用。至于建立一个标准,我会建议采用绝大多数杰克逊约定,但有一些例外:


  • 对象优先于基元。 / li>
  • 空集合优于空。

  • 没有值的对象表示为空。

  • 基元返回它们的值。



如果您要返回一个大多为空值的JSON对象,那么您可能有一个候选人重构为多个服务。

  {

value1:null,

value2:null,

text1:null,

text2:hello,

intValue:0,//只有在您绝对确定答案是0

myList:[],

myEmptyList:null,// NOT BEST PRACTICE - return [] instead

boolean1:null,//仅当您确信答案是真/假时才使用原语

littleboolean:false

}

上面的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;


$ b public static void main(String [] args)throws Exception {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new Data()));


$ / code $ / pre
$ b $ Maven依赖:

 < dependency> 
< 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}
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:[]}







tl; dr 这里:



JSON2 JSON规范表示应该表示 null 。但是,一如既往,这取决于你在做什么 - 有时候做正确的方式并不总是适合你的情况。使用您的判断并做出明智的决定。







JSON1 {}



这会返回一个空对象。这里没有数据,它只是告诉你,无论你寻找什么密钥(不管是 myCount 还是别的)都是类型未定义






JSON2 {myCount :null}



在这种情况下,实际定义 myCount ,尽管它的值是 null 。这是 not 与not undefined 并且不是 null 相同,if您正在测试一个条件或另一个条件,这可能会成功,而JSON1将失败。



这是表示 null per JSON规范






JSON3 {myCount:0}

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




JSON4 {myString:}

在这种情况下,你会得到一个空字符串。同样,与JSON2一样,它已被定义,但它是空的。你可以测试 if(obj.myString ==)但你不能测试 null undefined






JSON5 { myString:null}



这可能会让你陷入困境,因为你正在设置 string 值为null;在这种情况下, obj.myString ==null但它不是 == null






JSON6 {myArray:[]} $ b

这会告诉你数组 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

{
    "myStrung": ""
}

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 sited in that, as a community will be consuming greater numbers 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:

JSON2 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中表示空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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