Returning an empty list on Google App Engine behav

2019-05-29 03:16发布

问题:

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/