我有这个班:
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":"喜"}
答案 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);