Jackson field value with no quotation marks

10,318

Solution 1

As others have pointed out, double-quotes are not optional in JSON, but mandatory.

Having said that, you can use annotation JsonRawValue to do what you want.

public class POJO {
  public String name;
  @JsonRawValue
  public String click;
}

Solution 2

Well, technicaly you can do it. Although the result would not be a valid JSON, it is still possible with Jackson:

class Dto  {
    @JsonProperty("name")
    String foo = "nameValue";
    @JsonProperty("click")
    JsEntry entry = new JsEntry("function (e){console.log(\"message\");}");
}

class JsEntry implements JsonSerializableWithType {
    private String value;

    JsEntry(String value) {
        this.value = value;
    }

    @Override
    public void serializeWithType(JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException {
        this.serialize(jgen, provider);
    }

    @Override
    public void serialize(JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeRawValue(value);
    }
}

I'm fully agree, however, that this requirement causes a standard violation and should be revised.

Solution 3

That's not valid JSON, so you can't have it. JSON is a value transfer format, so you can't transfer functions.

If you really need to return functions in JSON, you can probably post-process the result in javascript.

Share:
10,318
ex0b1t
Author by

ex0b1t

I am passionate about Development and love to be challenged to find solutions to business problems. I strive to learn as much as possible and to make use of new and exciting technologies to get the work done faster and more efficiently. I have a background in development of JEE web-based enterprise portals, in a wide range of sectors, including Banking, Telecommunication and Risk & Security.

Updated on June 06, 2022

Comments

  • ex0b1t
    ex0b1t almost 2 years

    Is there a Annotation or some other way to tell Jackson to Serialize a String variables's value without quotation marks. The serializer should only serialize the one field's value without quotation marks.

    I am looking for a return of something similar to:

    {"name": "nameValue", "click" : function (e){console.log("message");}}
    

    instead of

    {"name": "nameValue", "click" : "function (e){console.log("message");}"}
    

    The above is how an external java script library requires the data, so if there is not a way i will have to manual alter the string after the Object Mapper has converted it to JSON.

  • ex0b1t
    ex0b1t over 10 years
    I know its not valid JSON. but that is the requirement.
  • Bozho
    Bozho over 10 years
    someone devised a bad requirement :) can you post-process the result with javascript after it comes back from the server?
  • ex0b1t
    ex0b1t over 10 years
    that's not a bad idea.