6

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
  • 1,292
  • 1
  • 17
  • 25

3 Answers3

14

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;
}
StaxMan
  • 113,358
  • 34
  • 211
  • 239
5

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.

Jk1
  • 11,233
  • 9
  • 54
  • 64
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.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140