简体   繁体   English

使用Gson与比较器序列化设置

[英]Serialize set with comparator using Gson

I need to serialize a class that contains a TreeSet for which it has a custom comparator (byte[] not being comparable). 我需要序列化一个包含TreeSet的类,该类具有一个自定义比较器(byte []不可比较)。

When I attempt to deserialize the class with Gson (v2.3.1) I get: 当我尝试使用Gson(v2.3.1)反序列化该类时,我得到:

Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(TreeMap.java:1290)
    at java.util.TreeMap.put(TreeMap.java:538)
    at java.util.TreeSet.add(TreeSet.java:255)....

So the TreeSet is not deserialized using the comparator. 因此,不使用比较器对TreeSet进行反序列化。

The class looks like this: 该类如下所示:

public class In {

    private final SortedSet<byte[]> keys = new TreeSet<>(new ByteKeyComparator());

}

Is there a way to make Gson understand that it needs a comparator for this set? 有没有一种方法可以使Gson理解它需要这个集合的比较器?

You're right, it's a serialization bug. 没错,这是一个序列化错误。 However, it has nothing to do with Gson, and actually your custom comparator is being retained. 但是,它与Gson无关,实际上保留了您的自定义比较器。

The problem lies in the implementation of TreeMap.put(K,V) combined with the deserialization behavior of an empty TreeSet, which results in the backing map having a null root . 问题在于TreeMap.put(K,V)的实现与空TreeSet的反序列化行为相结合,这导致支持映射的root为空。 If the TreeMap's root node is null and you put a key/value pair, it ignores the configured comparator. 如果TreeMap的根节点为null,并且您放置了键/值对,则它将忽略已配置的比较器。

To solve your problem, skip serializing empty TreeSet s. 要解决您的问题,请跳过序列空的TreeSet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM