Thrift无法将json反序列化为java对象[英] Thrift can not deserialize from json to java object

问题描述

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

<块引用>

序列化为"简单"JSON

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

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

(强调我的)

本文地址:https://www.itbaoku.cn/post/978614.html