在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>