Thrift can not deserialize from json to java object

泪湿孤枕 提交于 2019-12-04 02:01:36

问题


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:


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)



来源:https://stackoverflow.com/questions/24319325/thrift-can-not-deserialize-from-json-to-java-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!