Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson field value with no quotation marks

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.

like image 269
ex0b1t Avatar asked Aug 10 '13 17:08

ex0b1t


3 Answers

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;
}
like image 65
StaxMan Avatar answered Sep 29 '22 09:09

StaxMan


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.

like image 20
Jk1 Avatar answered Sep 29 '22 08:09

Jk1


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.

like image 37
Bozho Avatar answered Sep 29 '22 09:09

Bozho