简体   繁体   中英

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

I've got this code which currently sends JSON object via Jersey-client in java/groovy:

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

What I would like to do is to send that details map without converting it into JSONobject as I want to remove that dependency from my project. Is it possible to do? If I try .post(ClientResponse.class, details); it doesn't work as map is differently formatted than json. Any help would be greatly appreciated

If you use groovy.son.JsonBuilder as suggested by Aramiti, you might want to try something like the following:

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")

This would produce the following in Groovy console:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM