集的序列化 [英] Serialization of set

查看:94
本文介绍了集的序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写自己的Set序列化程序,特别是HashSet.这是因为此类包含枚举元素的集合的默认输出如下所示:

I am trying to write my own Set serializer, HashSet specifically. This because the default output of such a set holding enum elements looks like this:

modifier: {
    amount: 1
    criteriaSet: {
        class: java.util.HashSet //<--- bothers me
        items: [
            NONE                
            ADD
            MULTIPLY
        ]
    }
}

所以我想我写了自己的序列化器.这就是write方法的样子.

So I thought I write my own serializer. this is what the write method looks like.

@Override
public void write(Json json, HashSet object, Class knownType) {
    json.writeObjectStart();
    for (Object o : object)
    {
        if (o instanceof Modifier.Criteria)
            json.writeValue("name", ((Modifier.Criteria) o).name());
    }
    json.writeObjectEnd();
}

这有效,但是需要我命名该字段,因此输出是这样的:

This works but it requires me to name the field and thus the output is like this:

modifier: {
    amount: 1
    criteriaSet: {
        name: NONE
        name: ADD
        name: MULTIPLY
    }
}

这可行,但是因为默认的Set序列化程序不会写字段名称(name :),所以我也想要这样.仅写枚举名称会产生错误json.writeValue(((Modifier.Criteria) o).name());:java.lang.IllegalStateException: Name must be set.

This works but since the default Set serializer does not write the field names (name:) I want that too. Just writing the enum name yields an error json.writeValue(((Modifier.Criteria) o).name()); : java.lang.IllegalStateException: Name must be set.

我首先为EnumSet进行了尝试,因为EnumSetEnum组合的工作效率更高,但是我也遇到了问题.我正在寻找一种将Enum值存储到Set中的干净解决方案.

I have tried this for EnumSet first because EnumSet works more efficient with sets of Enum but I ran into problems too. I am looking for a clean solution to store Enum values into a Set.

推荐答案

我想您的意思是您希望它是一个json数组([..])而不是json对象({...}).在这种情况下,请使用writeArrayStart()writeArrayEnd().另请参阅: https://github.com/libgdx/libgdx/wiki /Reading-and-writing-JSON

I guess you mean that you want it to be an json array ([..]) instead of json object ({...}). In that case use writeArrayStart() and writeArrayEnd(). See also: https://github.com/libgdx/libgdx/wiki/Reading-and-writing-JSON

这篇关于集的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆