Jersey client send string with application/json type

3.4k Views Asked by At

I need to send a String that is already in JSON format using the Jersey client 1.19 and genson 1.3

Client.create().resource(path).webResource.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class, jsonAsString)

The problem with this is that the client is parsing the string, I need it to be sent as it is. I'm sending something like { "name":"Foo" } and the client is converting it to "{ \"name\":\"Foo\" }". If I change the type to PLAIN_TEXT it sends the request correctly but I need to send it as application/json .

3

There are 3 best solutions below

2
On BEST ANSWER

So yes Genson will try to encode your string as a literal json string. In this case it is maybe not what you would want, but more generally it is what people would expect: serialize à java string as a json string.

The solution I see is too extend GensonJsonConverter and override isWritable to return false when the input type is string. Then just register it. That should work.

I've opened this issue so it can be added as a more flexible feature.

1
On

Try changing MediaType.APPLICATION_JSON_TYPE to MediaType.APPLICATION_JSON http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/

0
On

I tried your code with Jersey 1.19, Genson 1.3 and Wireshark. It works fine without Genson so it appears Genson is treating it as a literal string (since it is of type String) and therefore quoting the double quotes.

The following works.

    String jsonAsString = "{ \"name\":\"Foo\" }";
    Map<String, String> map = (new Genson()).deserialize(jsonAsString, Map.class);
    String path = "...";
    ClientResponse resp = 
            Client.create().resource(path)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .put(ClientResponse.class, map);

I have used Map because it is sufficient for the example but you can deserialize it to the appropriate object.

If you looking for an option to specify that the string should be passed as is, I am not yet aware of it but this should at least provide a solution to the problem of sending that string as application/json.