在Google App Engine上返回空列表的行为在开发服务器上和部署时有所不同
我创建了一个返回项目列表的端点。当列表为空时,我期待在JSON中看到一个空列表,但列表字段被省略。这不是在开发服务器上发生的事情。
I've created an endpoint that returns a list of items. When the list is empty, I was expecting to see an empty list in the JSON, but the list field was instead omitted. That's not what happens on the dev server.
例:
Ex:
@ApiMethod(name = "udinic", path = "udinic")
public List<UdinicResponse> getUdinics() {
List<UdinicResponse> list = new ArrayList<>();
UdinicResponse res = new UdinicResponse();
res.bla = "sds";
list.add(res);
return list;
}
static class UdinicResponse {
String bla;
public String getBla() {
return bla;
}
public void setBla(String bla) {
this.bla = bla;
}
}
当我在dev服务器上运行这个时,我得到的答复:
When I run this on the dev server, that's the response I get:
{
items: [ ]
}
当它位于部署的服务器上时,这就是我得到的结果:
When it's on the deployed server, that's what I get:
{
kind: "udinicEndpoint#resourcesItem",
etag: ""3Ms41gaYW9qnDr8JAXr8FIDhu9jVetg""
}
任何想法如何获得一致的行为?我希望获得一个空列表,而不是省略该字段。
Any ideas how can I get a consistent behavior? I prefer to get an empty list instead of omitting the field.
预期的行为是空列表将被省略根据文档[1]:
The expected behavior is that empty lists will be omitted, as per the documentation [1]:
返回的空列表将作为客户端的空值到达。
记得检查这些。
Empty Lists that are returned will arrive as nulls on the client-side. Remember to check for those.
所以实际的问题是开发服务器与生产不一致。作为开发服务器一致性的解决方法,您可以添加对空列表的检查,并返回null。
So the actual issue is the development server is not consistent with production. As a workaround for consistency on the development server, you can add a check for an empty list and return null instead.
return list.isEmpty() ? null : list;
[1] https://cloud.google.com/solutions/mobile/google-cloud-endpoints-for-android/