序列化对象时更改字段名称

时间:2016-02-14 09:11:34

标签: java json serialization boon

我有这个班:

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;
    }
}

我创建了一个对象并将其序列化,但字段名称未更改

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

我希望js1变量类似于:{" message_id":" 1"," message":" hi"}
但它是:{" id":" 1"," msg":" hi"," id": " 1"" MSG":"喜"}

2 个答案:

答案 0 :(得分:1)

不确定Boon,但这是Gson序列化Object的方法,导入String或{{}可能存在问题1}},请检查一下。此示例以显示的输出运行。该代码也可在Github上找到

SerializedName

  

输出

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

/**
 * Created by Pankaj Nimgade on 14-02-2016.
 */
public class TestDriveOne {

    public static void main(String[] args) {
        QueuedMessage queuedMessage = new QueuedMessage("123", "Hello World");
        System.out.println((new Gson()).toJson(queuedMessage));
    }


}

class QueuedMessage {

    @SerializedName("message_id")
    private String id;

    @SerializedName("message")
    private String msg;

    public QueuedMessage() {
    }

    public QueuedMessage(String id, String msg) {
        this.id = id;
        this.msg = 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;
    }
}

答案 1 :(得分:1)

您需要告诉JsonFactory使用注释:

ObjectMapper json = JsonFactory.createUseAnnotations(true);