0

I wasn't sure how to name this question, my apologies.

I have a POJO containing a byte[] field. When writing to the database, I want the binary object, but when sending the JSON to the client for display, I want the String representation. I'm not sure how to get there though with this implementation of my POJO. Any tips on annotations would be appreciated.

public class MyClass
{
    private int id_;
    private byte[] data_;

    /**
     * Constructor
     */
    public MyClass(int id, byte[] data){
        id_ = id;
        data_ = data;
    }

    @JsonSetter("id")
    public void setId(int id){
        id_ = id;
    }

    @JsonGetter("id")
    public int getId(){
        return id_;
    }

    @JsonSetter("data")
    public void setData(byte[] data){
        data_ = data;
    }

    @JsonGetter("data")
    public byte[] getData(){
        return data_;
    }

    @JsonSetter("dataString")
    public void setData(String data){
        data_ = data.getBytes();
    }

    @JsonGetter("dataString")
    public String getDataString(){
        String dataString = new String();

        if(data_ != null)
        {
            dataString = new String(data_);
        }

        return dataString;
    }

}

With this implementation, my client is displaying the byte[], which is obviously not human readable. It is important to store the binary object in the database, but I've got to be able to actually read it in the client.

I'm wondering if there's some way to do something like the following pseudo code

ObjectMapper mapper = new ObjectMapper();
MyClass object = new MyClass(1, new byte[]{19, 25, 17, 29});

if(database interaction)
{
    mapper.configure.ignoreSomeJsonGetterAnnotation("dataString");
}
else if(client interaction)
{
    mapper.configure.ignoreSomeJsonGetterAnnotation("data");
}
String json = mapper.writeValueAsString(object);

Thanks in advance.

jseashell
  • 745
  • 9
  • 19

0 Answers0