如何在 Jersey rest 客户端 Post 请求中将 groovy 地图作为参数发送?

How to send groovy map as a parameter in Jersey rest client Post request?

我有这段代码,目前通过 java/groovy 中的 Jersey 客户端发送 JSON 对象:

 webResource = client
                     .resource(endPointUrl)
                     .header("Content-Type", "application/json");
 def details = [
                name  : nameVar,
                start : startDate,
                end   : endDate,
                status: 1
                ]

 JSONObject jsonString = new JSONObject(details);

 ClientResponse response = webResource
                      .header("Content-Type", "application/json")
                      .header('Cookie', userCookie)
                      .post(ClientResponse.class, jsonString); 

我想做的是发送 details 地图而不将其转换为 JSONobject,因为我想从我的项目中删除该依赖项。有可能吗?如果我尝试 .post(ClientResponse.class, details); 它不起作用,因为地图的格式与 json 不同。任何帮助将不胜感激

如果您按照 Aramiti 的建议使用 groovy.son.JsonBuilder,您可能想尝试如下操作:

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

/**
 * Create JSON from the specified map.
 * @param map Map to convert to JSON
 * @return JSON text
 */
private buildJSONFromMap(map) {
  def builder = new JsonBuilder()

  builder {
    map.each { key, value ->
      "$key" "$value"
    }
  }

  builder.toString()
}

/**
 * Convert JSON back to map.
 * @param JSON text to convert.
 * @return Object (a map in this case)
 */
private rebuildMapFromJSON(json) {
  new JsonSlurper().parseText(json)
}

def details = [
    name  : "nameVar",
    start : "startDate",
    end   : "endDate",
    status: 1
]

/* Build JSON on client side */
def json = buildJSONFromMap(details)
println("JSON: $json")

/* Consume JSON/convert to usable object */
def rebuiltMap = rebuildMapFromJSON(json)
print("Rebuilt MAP: $rebuiltMap")

这将在 Groovy 控制台中产生以下内容:

JSON: {"name":"nameVar","start":"startDate","end":"endDate","status":"1"}
Rebuilt MAP: [status:1, start:startDate, name:nameVar, end:endDate]