Java 使用集合序列化<;T扩展TBase>;

Java 使用集合序列化<;T扩展TBase>;,java,json,serialization,thrift,Java,Json,Serialization,Thrift,我有一个由thrift struct生成的thrift类: struct Chapter { 1: required i32 id, 2: optional string name, 3: optional string desc, 4: optional i32 questionCount, 5: optional i32 keypointId, } 据我所知,我们可以使用TSimpleJSONProtocol.Factory来序列化没有setXXX和

我有一个由thrift struct生成的thrift类:

struct Chapter {
    1: required i32 id,
    2: optional string name,
    3: optional string desc,
    4: optional i32 questionCount,
    5: optional i32 keypointId,
}
据我所知,我们可以使用TSimpleJSONProtocol.Factory来序列化没有setXXX和null成员的对象。 但是,如何序列化章节对象列表。当我使用Jackson时,必须有一些setXXX,如下所示:

[{"name":"ch1","desc":null,"questionCount":0,"keypointId":1,"setName":true,"setDesc":false,"setQuestionCount":false,"setKeypointId":true},{"name":"ch2","desc":null,"questionCount":0,"keypointId":2,"setName":true,"setDesc":false,"setQuestionCount":false,"setKeypointId":true}]
但我需要的是:

[{"name":"ch1","keypointId":1},{"name":"ch2","keypointId":2}]
我的简单解决方案是连接每个对象:

public static <T extends TBase> String writeValuewithTBase(Collection<T> c) {
    try {
        if (c == null) {
            return null;
        } else if (c.isEmpty()) {
            return "[]";
        }

        return c.stream().map(t -> {
            try {
                return ThriftSerDePool.getSimpleJsonSerializer().toString(t);
            } catch (TException e) {
                LOG.warn("Failed to serialize object to JSON string", e);
                throw new RuntimeException(e);
            }
        }).collect(Collectors.joining(",", "[", "]"));
    } catch (Exception e) {
        LOG.warn("Failed to serialize object to JSON string", e);
        return "";
    }

}
public静态字符串writeValue WithtBase(集合c){
试一试{
如果(c==null){
返回null;
}else if(c.isEmpty()){
返回“[]”;
}
返回c.stream().map(t->{
试一试{
返回ThriftSerDePool.getSimpleJsonSerializer().toString(t);
}捕获(特克斯){
LOG.warn(“未能将对象序列化为JSON字符串”,e);
抛出新的运行时异常(e);
}
}).collect(收集器.连接(“,”,“[”,“]));
}捕获(例外e){
LOG.warn(“未能将对象序列化为JSON字符串”,e);
返回“”;
}
}

有什么好主意吗,比如使用Jackson的自定义序列化程序,对你的问题没有什么特别的,但是我建议使用TJsonProtocol而不是TSimpleJsonProtocol-。我只是说,它可以通过Jackson的readValue方法反序列化。不管怎样,这都是你的数据。你的问题没有什么特别的,但我建议使用TJsonProtocol而不是TSimpleJsonProtocol-。我只是说,它可以通过jackson的readValue方法反序列化。反正是你的数据。