Returning an empty list on Google App Engine behaves differently on the dev server and when deployed

流过昼夜 提交于 2019-12-10 10:47:28

问题


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;
    }
}

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.

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/



来源:https://stackoverflow.com/questions/33483121/returning-an-empty-list-on-google-app-engine-behaves-differently-on-the-dev-serv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!