Michael Levy Michael Levy - 1 year ago 114
Java Question

Java Jersey JSON service doesn't return quoted string?

Here is a simple Web Service written using Jersey

@GET
@Produces(MediaType.APPLICATION_JSON)
public Object interpretationJson() {
String o = "a simple string";
return o;
}


The response for this is:

HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
Date: Mon, 02 Oct 2017 23:18:14 GMT

a simple string


Shouldn't the string in the response body be quoted? I don't believe this is valid JSON. Shouldn't the response be:

HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
Date: Mon, 02 Oct 2017 23:18:14 GMT

"a simple string"


This caused me a bit of confusion. I originally thought the problem was on the client side, but now I think the problem is the string returned from Jersey is not valid JSON - C# Parsing json that may have simple types

Answer Source

Here is a quote attributed to Jackson's developer (Tatu Saloranta / cowtowncoder) about why a simple string is treated this way.

This is not the reason String is declared untouchable. Rather, choice is between:

Write input String as JSON String, i.e. surround it with double-quotes and escape necessary characters, or

Write String exactly as-is, assuming user wanted to produce exactly that output (presumable hand-encoded JSON).

Since there is no metadata to tell what is user's intention, Jackson is being conservative and using latter choice. This is also prudent considering that JSON Specification only considers JSON Objects and JSON Arrays as valid JSON content -- so strictly speaking, returning a JSON String would produce invalid JSON anyway.

Referenced issue...

"Untouchable" is Jackson's term for a type that will be returned exactly as is.

You can easily return a string with quotes if you want to and there are several ways to do it. But that was not your question, I think.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download