【问题标题】:Serialize a enum with Collection properties to JSON string将具有 Collection 属性的枚举序列化为 JSON 字符串
【发布时间】:2015-09-07 09:48:19
【问题描述】:

在 ReceivePartyPlaylistEvent 对象下方,我尝试使用 GSON 库进行序列化。这与播放列表和歌曲类有关联。

public final class ReceivePartyPlaylistEvent extends Event {
        private PartyPlayList partyPlayList;

}

并且 PartyPlaylist 是一个 枚举,因为我需要它是 单个实例

    public enum PartyPlayList implements Playlist{
    INSTANCE;

    private List<Song> songList = new ArrayList<>();

    public List<Song> getSongList() {
        return songList;
    }
}

和歌曲对象一样。两个类扩展了这个 Song 对象并实现了抽象方法。

    public abstract class Song{
    private String songID;
    private String trackTitle;
    private String trackAlbum;
    private String trackArtist;
    private String albumArtUrl;
    .... setters and getters...

    }

现在,当我尝试使用 GSON(2.2.4) 序列化 ReceivePartyPlaylistEvent 时,它给了我一个空白输出。 那么我该如何序列化呢。

序列化:

//_receivePartyPlaylistEvent has dummy values in it.
    Gson gson = new Gson();
    return gson.toJson(_receivePartyPlaylistEvent );

【问题讨论】:

    标签: java json serialization enums deserialization


    【解决方案1】:

    你还没有给partyPlayList分配任何东西,所以它默认为null,Gson不会序列化它。

    试试:

    private PartyPlayList partyPlayList = PartyPlayList.INSTANCE;
    

    【讨论】:

    • 不,不是这样,在测试用例中,我添加了带有歌曲集合的虚拟播放列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2012-02-27
    • 2012-05-10
    • 1970-01-01
    相关资源
    最近更新 更多