4

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

Michael Levy
  • 13,097
  • 15
  • 66
  • 100
  • Why? To get a quoted string, escape and add another set of quotes. If you will return a proper json, instead of just string, then value of field will be properly quoted – Optional Oct 03 '17 at 00:38
  • The serializer should properly serialize the object being returned. The string without quotes is not valid JSON. This is a simplified example. In the actual code the object "o" is sometimes a simple string, but sometimes is a more complex object. – Michael Levy Oct 03 '17 at 00:47

2 Answers2

4

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.

joshp
  • 1,886
  • 2
  • 20
  • 28
  • Thanks. Is there a recommend way to wrap the untouchable string in quotes? or is something like the following good enough: Object o = getObjectFromSomewhere(); if (o instanceof String) { String s = String.format("\"%s\"", (String)o); return s; } else { return o; } – Michael Levy Oct 03 '17 at 12:40
-1
public class TestGetterSetter{

private String name ;

public void setName(String name){
    this.name = name ;
}


public String getName(String name){
    return this.name ;
}}

Using this POJO class Set the value and return this POJO Class Object

Er Kapil Mehta
  • 79
  • 2
  • 11