Reputation: 5307
I have a REST API implemented using Jersey, I am using the Jackson feature for automatically serialize objects to JSON, there is a special case where I need to return a JSON string that represents an script. As the script can have different unknown structures I cannot just serialize it to an Object, that script comes from a column in a db table. At the same time I have a full Script object that contains all the information of the DB including the script string as a String property.
What I want is to tell Jersey-Jackson not to serialize (skip) the endpoint GET /script/{scriptId}, look at the code:
@Path("script")
@Produces(MediaType.APPLICATION_JSON)
public class ScriptResource {
private ScriptService service;
@GET
@Path("{scriptId}")
public String getScript(@NotNull @PathParam("scriptId") Integer scriptId) {
return service.getScript(scriptId); // returns a a valid JSON String
}
@GET
@Path("full/{scriptId}")
public Script getFullScript(@NotNull @PathParam("scriptId") Integer scriptId) {
return service.getFullScript(scriptId); // returns a Script object
}
}
The @Produces annotation is the one that triggers the automatic transformation via Jackson, I would like to configure Jackson and exlude the resource endpoint that I don't want to be converted automatically.
I don't want to:
Upvotes: 0
Views: 1461
Reputation: 10853
One more option which you can consider in addition to those mentioned by @wasabi, is having a wrapper class for your string which would customize the Jackson serialization so it would not be converted to JSON. That can be done by using the combination of the @JsonValue
and @JsonRawValue
annotations on the getter method.
Here is an example wrapper:
public class RawJsonString {
private final String json;
public RawJsonString(String json) {
this.json = json;
}
@JsonRawValue
@JsonValue
public String getJson() {
return json;
}
}
... then your modified resource method would look as follows:
@GET
@Path("{scriptId}")
public JsonRawString getScript(@NotNull @PathParam("scriptId") Integer scriptId) {
return new JsonRawString(service.getScript(scriptId)); // returns a a valid JSON String
}
Upvotes: 2
Reputation: 381
If you just want to make sure that some fields in Script
class would not be serialized by Jackson, you could easily do so by annotating such fields with @JsonIgnore.
If you would like to have more control over the generated JSON, I would implement a custom JsonSerializer, and refer to it using @JsonSerialize annotation in your Script
class. See this post for an example.
If you cannot modify Script
class, you could also implement a MessageBodyWriter. See this post for an example.
Upvotes: 1