从映射中删除具有空值的键,以便它们不包含在 REST GET 请求的查询中

Removing a key with empty values from a map so they are not included in a query of a REST GET request

我有一个查询 class,其中包含我可以发送的查询:

Class Query {
   Integer product_id
   Integer collection_id
   Integer id
}

我使用 object 映射器将我的查询 object 转换为这样的映射:

def q = new Query(product_id: 12345)
Map <String, Object> toMap = new ObjectMapper().convertValue( q, Map )

然后我依次传递我的 RESTClient,因此它包含在请求中

def client = new RESTClient ('http://somewebsite.com')
client.get(path: 'somePath/anotherPath.json',
           contentType: ContentType.JSON,
           query: q)

在我发送请求后,查询映射中的空键也在请求中发送,导致响应出现问题

GET somePath/anotherPath.json?product_id=12345&collection_id=&id=

正如标题所说,有没有一种方法可以删除映射中具有空值的键,以便在您发送 REST GET 请求时它们不包含在请求中。我希望它是这样的:

GET somePath/anotherPath.json?product_id=12345

请求中未发送具有空值(collection_id 和 id)的键。

可以使用注解@JsonInclude(Include.NON_NULL)

Class Query {

   @JsonInclude(Include.NON_NULL)
   Integer product_id
   ...
}

查看文档 here

ObjectMapper 没有任何参数可以禁止导出空值吗?

如果没有,你可以这样做:

Map <String, Object> toMap = new ObjectMapper().convertValue(q, Map).findAll { it.value != null }