java - Thrift 无法从 json 反序列化为 java 对象

标签 java json thrift thrift-protocol

我从以下 thrift 对象生成了一个 java 对象:

struct Account {
    1: required string accountType,
    2: bool accountActive,
}

我写了一个 java 代码试图将 java 对象序列化为 json 字符串,然后将 json 字符串反序列化回 java 对象。我可以成功序列化但无法反序列化。

    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
    TDeserializer deserializer = new TDeserializer(new TSimpleJSONProtocol.Factory());

    Account a1 = new Account();
    a1.setAccountType("P");
    a1.setAccountActive(true);

    String json = serializer.toString(a1);
    System.out.println(json);

    Account a2 = new Account();
    deserializer.deserialize(a2, json, "UTF-8");
    System.out.println(a2);
    System.out.println(a2.getAccountType());

它不断抛出以下异常:

Exception in thread "main" org.apache.thrift.protocol.TProtocolException: Required field 'accountType' was not present! Struct: Account(accountType:null, accountActive:false)

谁能帮我找出问题所在? 提前致谢!

最佳答案

SimpleJSONProtocol 从未打算反序列化。请改用 TJSONProtocol

来自 http://wiki.apache.org/thrift/ThriftUsageJava :

Serializing to "Simple" JSON

TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(work);

The "Simple" JSON protocol produces output suitable for AJAX or scripting languages. It does not preserve Thrift's field tags and cannot be read back in by Thrift.

(强调我的)

关于java - Thrift 无法从 json 反序列化为 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319325/

相关文章:

java - 为什么可以在 Java 接口(interface)方法上调用方法? [可比]

HBase 节俭 : how to connect to remote HBase master/cluster?

java - 在 spring boot 中添加外部静态文件(css、js、png ...)

java - hibernate 异常 : Couldn't obtain transaction-synchronized Session for current thread

java - JSON 解析器错误

javascript - jquery/backbone/mustache/json 将 html 渲染为文本字符串

c++ - 编译 Thrift 服务器时出错

java - 尝试使用 thrift 的 TFileTransport 和 TFileProcessor 让 Python 客户端与 Java 服务器对话

java - 登录后在抽屉导航中显示电子邮件

php - 通过 PHP 连接到 MySQL 的 JSON Web 钩子(Hook)