Using JacksonJson @JsonSerialiser annotation for a single property

By Dave Elkan

When using Spring MVC and the Jackson JSON processor recently, I needed to only expose one property from a referenced object when serialising.

Rather than have a new object defined with the single property, I used the @JsonSerialiser annotation to serialise only the property I was interested in.

I will use a ‘PublicFile’ Object as an example.

public class PublicFile {
  private String path;

  public String getPath() {
    return path;
  }

  public void setPath(String path) {
    this.path = path;
  }
}

If we were to serialise the an instance of this PublicFile Object using the Jackson Json processor, the result would be:

{
    "publicfile": {
        "path": "file path value"
    }
}

To return only the path property when serialising the instance to JSON, create a serialiser like:

public class PublicFilePathJsonSerialiser extends JsonSerializer<PublicFile> {
    @Override
    public void serialize(PublicFile file, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeString(file.getPath());
    }
}

And then reference it in your class:

@JsonSerialize(using = PublicFilePathJsonSerialiser.class)
public class PublicFile {
  private String path;

  public String getPath() {
    return path;
  }

  public void setPath(String path) {
    this.path = path;
  }
}

This produces:

{
    "publicfile": "file path value"
}
comments powered by Disqus