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

时间:2016-01-21 17:36:24

标签: json rest groovy jersey jersey-client

我有这个代码,目前通过java / groovy中的Jersey-client发送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不同。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

如果您按照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]