Reputation: 1342
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.
Upvotes: 7
Views: 13637
Reputation: 116502
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;
}
Upvotes: 16
Reputation: 11443
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.
Upvotes: 6
Reputation: 597076
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.
Upvotes: 3