1

I have a thrift class generated by thrift struct:

struct Chapter {
    1: required i32 id,
    2: optional string name,
    3: optional string desc,
    4: optional i32 questionCount,
    5: optional i32 keypointId,
}

as far as i know, we can use TSimpleJSONProtocol.Factory to serialize the object without setXXX and null members. But, how to serialize a list of Chapter objects. when i using Jackson, there must be some setXXX, as follows:

[{"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}]

But what i need is:

[{"name":"ch1","keypointId":1},{"name":"ch2","keypointId":2}]

My simple solution is joining every object:

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

}

Is any good idea, like using Jackson's Custom_Serializers

JensG
  • 13,148
  • 4
  • 45
  • 55
Feiyu Zhou
  • 4,344
  • 32
  • 36
  • Nothing in particular to your question, but I'd recommend to use TJsonProtocol rather than TSimpleJsonProtocol - [the latter was only intended to be written, never to be read back](http://stackoverflow.com/questions/24319325/thrift-can-not-deserialize-from-json-to-java-object). – JensG Nov 15 '15 at 14:47
  • It can be deserialize by jackson's readValue method – Feiyu Zhou Nov 15 '15 at 15:05
  • I'm just saying. It's your data anyway. – JensG Nov 15 '15 at 15:40

0 Answers0