[英]Gson: enum serialization issue in bean
My SegmentCreateRequest bean class: 我的SegmentCreateRequest bean类:
public class SegmentCreateRequest {
@SerializedName("name")
private String segmentName;
private SegmentSource segmentSource;
public String getSegmentName() {
return segmentName;
}
public void setSegmentName(String segmentName) {
this.segmentName = segmentName;
}
public SegmentSource getSegmentSource() {
return segmentSource;
}
public void setSegmentSource(SegmentSource segmentSource) {
this.segmentSource = segmentSource;
}
public enum SegmentSource {
@SerializedName("followed") FOLLOWED,
@SerializedName("impressed") IMPRESSED,
@SerializedName("engaged") ENGAGED,
@SerializedName("tailored") TAILORED;
@SerializedName("user_ids")
private List<String> userIds;
SegmentSource(){
this.userIds = Lists.newArrayList();
}
public void setUserIds(List<String> userIds) {
this.userIds = userIds;
}
public List<String> getUserIds() {
return this.userIds;
}
public SegmentSource userIds(List<String> userIds) {
this.userIds = userIds;
return this;
}
}
}
The segmentSource
field name should change according to the value of the enum. segmentSource
字段名称应根据枚举的值更改。
I was expecting object serialization of this class to return something like: 我期望此类的对象序列化返回类似以下内容:
{
"name":"segment101",
"followed":{"user_ids":["1234567890"]}
}
However, it returns: 但是,它返回:
{"name":"skumar-3020-seg","segmentSource":"followed"}
using Google Gson for serialization/deserialization. 使用Google Gson进行序列化/反序列化。
How do I setup my bean to achieve the required serialization? 如何设置我的bean以实现所需的序列化?
You are serializing an enum instance into a field named segmentSource . 您正在将枚举实例序列化到名为segmentSource的字段中 。
The name of that field is not name! 该字段的名称不是名称!
Beyond that, there is also a potential bug in your code: enums are singeltons! 除此之外,您的代码中还存在一个潜在的错误:枚举就是singeltons! There will be one instance of FOLLOWED for example. 例如,将有一个 FOLLOWED实例。 This means: any change to the list of FOLLOWED is visible "globally". 这意味着:对FOLLOWED列表的任何更改都是“全局”可见的。 There is no such thing as having two different SegmentCreateRequests then (in parallel). 然后没有(并行)具有两个不同的SegmentCreateRequests。
In other words: when you create some 换句话说:当您创建一些
SegmentCreateRequests reqA = ...
with some specific users on FOLLOWED; 与某些特定用户一起关注; but you do 但你做了
SegmentCreateRequests reqB = ...
in parallel, then those two requests objects will be working on the same list in the end. 并行地,那么这两个请求对象最终将在同一列表上工作。 Meaning: your code isn't thread safe. 含义:您的代码不是线程安全的。 Thus: that list of users must not go into the enum constant. 因此:该用户列表一定不能进入枚举常量。 It should rather be a property of the surrounding request! 它应该是周围请求的属性!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.