Search code examples
javajsonserializationboon

change field name when serializing object


I have this class:

import org.boon.json.annotations.SerializedName;

public class QueuedMessage {

    @SerializedName("message_id")
    String id;

    @SerializedName("message")
    String msg;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

I create an object and serialize it, but field names are not changed

    QueuedMessage qm = new QueuedMessage();
    qm.setId("1");
    qm.setMsg("hi");
    String js1 = json.toJson(qm);

I expect js1 variable be something like: {"message_id":"1","message":"hi"}
but it is: {"id":"1","msg":"hi","id":"1","msg":"hi"}


Solution

  • You need to tell the JsonFactory to use annotations:

    ObjectMapper json = JsonFactory.createUseAnnotations(true);