Thrift can not deserialize from json to java objec

2020-03-31 04:23发布

I generated a java object from the following thrift object:

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

I wrote a java code trying to serialize java object to json string and then deserialize the json string back to java object. I can serialize successfully but failed to deserialize.

    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());

It keeps throwing the following exception:

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

Can anyone help me figure out what's the issue? Thanks in advance!

1条回答
Bombasti
2楼-- · 2020-03-31 05:05

The SimpleJSONProtocol was never intended to be deserializable. Use TJSONProtocol instead.

From 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.

(emphasis mine)

查看更多
登录 后发表回答