Serialization of set

谁说我不能喝 提交于 2019-12-25 08:04:38

问题


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
        ]
    }
}

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
    }
}

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.

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.


回答1:


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



来源:https://stackoverflow.com/questions/40914151/serialization-of-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!