loc*_*ost 12 android json jackson
我的JSON结构:
{
...
"type":"post", // Type could vary
"items":[] // Array of items, each item is typeOf("type")
...
}
Run Code Online (Sandbox Code Playgroud)
如何items在我的POJO中反序列化并正确包裹列表:
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
}
Run Code Online (Sandbox Code Playgroud)
对于parcel类型列表,CREATOR应该提供一个对象,显然,该接口不能具有该对象.我应该使用抽象类而不是接口吗?
好吧,由于 Jackson 期望每个列表元素都有类型信息,并且我不想为这个 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();
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个基类,我的所有子类型项目都必须扩展它。
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;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
最后是我的 POJO 类:
public class NewsFeedEnvelope {
// ...
@JsonProperty("rows")
private List<FeedItem> items;
// ...
}
Run Code Online (Sandbox Code Playgroud)
现在 POJO 已被 Jackson 成功自动反序列化,无需任何自定义反序列化器。
| 归档时间: |
|
| 查看次数: |
1360 次 |
| 最近记录: |