我有一个由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成员。 但是,如何序列化Chapter对象列表。当我使用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 "";
}
}
有任何好主意,比如使用Jackson的Custom_Serializers