我的JSON结构:
{
...
"type":"post", // Type could vary
"items":[] // Array of items, each item is typeOf("type")
...
} 如何在POJO中反序列化并正确包装items列表:
public class ItemsEnvelope {
private String type;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type",
visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = A.class, name = "A"),
@JsonSubTypes.Type(value = B.class, name = "B"),
@JsonSubTypes.Type(value = C.class, name = "C")
})
private List<Item> items;
interface Item extends Parcelable {}
class A implements Item {
// Bunch of getters/setters and Parcelable methods/constructor
}
class B implements Item {
// Bunch of getters/setters and Parcelable methods/constructor
}
class C implements Item {
// Bunch of getters/setters and Parcelable methods/constructor
}
// Bunch of getters/setters and Parcelable methods/constructor
}对于包类型列表,应该提供一个CREATOR对象,而接口显然不能提供这个对象。我应该使用抽象类而不是接口吗?
发布于 2015-08-06 12:46:58
因为Jackson希望每个list元素都有类型信息,所以我不想为这个POJO编写自定义反序列化器--我用另一种方式解决了它。
首先,我做了一个接口,我的所有子类型项都必须实现这个接口。
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type",
visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = PostFeedItem.class, name = BaseFeedItem.TYPE_POST),
@JsonSubTypes.Type(value = PhotoFeedItem.class, name = BaseFeedItem.TYPE_PHOTO),
@JsonSubTypes.Type(value = AudioFeedItem.class, name = BaseFeedItem.TYPE_AUDIO),
@JsonSubTypes.Type(value = VideoFeedItem.class, name = BaseFeedItem.TYPE_VIDEO),
@JsonSubTypes.Type(value = FriendFeedItem.class, name = BaseFeedItem.TYPE_FRIEND)
})
public interface FeedItem extends Parcelable {
// ...
@BaseFeedItem.Type
String getType();
// ...
}然后我创建了一个基类,我的所有子类型项都必须扩展这个类。
public abstract class BaseFeedItem implements FeedItem {
public static final String TYPE_POST = "post";
public static final String TYPE_COMMUNITY_POST = "group_post";
public static final String TYPE_PHOTO = "photo";
public static final String TYPE_AUDIO = "audio";
public static final String TYPE_VIDEO = "video";
public static final String TYPE_FRIEND = "friend";
@Retention(RetentionPolicy.SOURCE)
@StringDef({TYPE_POST, TYPE_COMMUNITY_POST, TYPE_PHOTO, TYPE_AUDIO, TYPE_VIDEO, TYPE_FRIEND})
public @interface Type {}
private String type;
@Type
public String getType() {
return type;
}
// ...
}最后,我的POJO课程:
public class NewsFeedEnvelope {
// ...
@JsonProperty("rows")
private List<FeedItem> items;
// ...
}现在,POJO已由Jackson成功地自动反序列化,而没有任何自定义反序列化器。
发布于 2015-07-28 22:35:02
首先要做的事情是:只有当值包含在另一个对象(POJO)中时,EXTERNAL_PROPERTY才能工作;而对List、数组或Map不起作用。
如果您使用的是其他一种包含方法,则应该可以将内容序列化为JSON,并按预期读取生成的JSON回保持类型。也就是说,当开始使用Java对象时,支持双向序列化。除此之外,还可以支持一些JSON编码结构;但这取决于您试图支持的确切结构类型。
https://stackoverflow.com/questions/31638418
复制相似问题