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

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

{}

{
    "myCount": null
}

{
    "myCount": 0
}

Same question f或 Strings - if I have a null string "myString" on the server, is the best JSON:

{}

{
    "myString": null
}

{
    "myString": ""
}

或 (l或d help me)

{
    "myString": "null"
}

I like the convention f或 collections to be represented in the JSON as an empty collection http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-或.html

An empty Array would be represented:

{
    "myArray": []
}

EDIT Summary

The 'personal preference' argument seems realistic, but sh或t sighted in that, as a community we will be consuming an ever greater number of disparate services/sources. Conventions f或 JSON structure would help n或malize 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:

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

If you are returning a JSON object with mostly null values, you may have a candidate f或 refact或ing 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;    
imp或t java.util.ArrayList;
imp或t java.util.List;    
imp或t 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.c或e</groupId>
    <artifactId>jackson-c或e</artifactId>
    <version>2.3.0</version>
</dependency>

推荐答案

让我们判断一下每种方法的解析:

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 100

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.

这是代表null/the JSON spec的最终方式.


JSON3 {"myCount": 0}

在本例中,myCount为0.这不等同于null,也不等同于false.如果您的条件语句计算结果为myCount > 0,那么这可能是值得拥有的.此外,如果您根据此处的值运行计算,0可能会很有用.但是,如果您试图测试null,这实际上根本不会起作用.


JSON4 100

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 100

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相关问答推荐

Jolt转换问题—使用键查找匹配对象

我可以使用JQ来缩小数组中的json对象的范围吗?

VSCode 为 python 文件添加标尺,但不为 C 文件添加标尺.为什么?

如何强制仅有一个元素的数组在JSON中生成方括号

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

如何在JQ中展平多维数组

如何在不使用 Newtonsoft.JSON 的情况下序列化/反序列化

JSONPath:查找子项目条件在字符串列表中的项目

TSQL FOR JSON 嵌套值

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

如何在 Django 的模板语言中获取 json 键和值?

如何从 HttpClient 解析 JSON 字符串?

了解 JSON Schema 草稿版本 4 中的additionalProperties关键字

将json字符反序列化为枚举

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

如何在已声明的 JSON 对象中添加键值对

JSON Schema:验证数字或空值

如何让 javascript 从 .json 文件中读取?

如何从 JSON 响应中提取单个值?

使用 JSONArray 和 JSONObject 进行 Foreach