How to convert thrift objects to readable string and convert it back?

时间:2015-07-31 19:20:50

标签: java json thrift thrift-protocol

Sometimes, we need to create some thrift objects in unit tests. We can do it by manually create object using Java code, like:

MyObj myObj = new MyObj();
myObj.setName("???");
myObj.setAge(111);

But which is not convenient. I'm looking for a way to create objects with some readable text.

We can convert thrift objects to JSON with TSimpleJSONProtocol, and get very readable JSON string, like:

{ "name": "???", "age": 111 }

But the problem is TSimpleJSONProtocol is write only, thrift can't read it back to construct an instance of MyObj.

Although there is a TJSONProtocol which supports to serialize and deserialize, but the generated JSON is not readable, it uses a very simplified JSON format and most of the field names are missing. Not convenient to construct it in tests.

Is there any way to convert thrift objects to readable string and also can convert it back? If TSimpleJSONProtocol supports converting back, which is just what I'm looking for

1 个答案:

答案 0 :(得分:1)

Thrift的主要目标是提供高效的序列化和RPC机制。你想要的是 - 至少部分 - 与此相反的东西。人类可读的数据结构和机器处理效率在很大程度上是相互冲突的目标,而Thrift则更倾向于后者。

您已经了解了TSimpleJsonTJson协议以及它们的优缺点,因此没有太多要补充的内容。唯一要说的是:Thrift的协议/传输堆栈非常简单。

这种简单性使得可以根据您的特定需求添加其他协议,而无需太多或过于复杂的工作。人们甚至可能在短时间内编写XML协议(如果有人真的想要这样的英国媒体报道)。

唯一需要注意的是, Thrift需要字段ID来反序列化数据。因此,您需要将它们存储在数据中,或者您需要一些能够根据字段和结构名称检索该字段ID的其他机制。