【问题标题】:Thrift can not deserialize from json to java objectThrift 无法从 json 反序列化为 java 对象
【发布时间】:2014-08-10 17:49:25
【问题描述】:

我从以下 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)

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

【问题讨论】:

  • thrift从java对象序列化的json字符串结果为{"accountType":"P","accountActive":1}

标签: java json thrift thrift-protocol


【解决方案1】:

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

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

序列化为“简单”JSON

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

“简单”JSON 协议生成适合 AJAX 或脚本语言的输出。它不保留 Thrift 的字段标签,并且不能被 Thrift 读回。

(强调我的)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2014-08-04
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多