1

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!

dereck
  • 499
  • 1
  • 10
  • 20
  • The json string result that serialized by thrift from java object is {"accountType":"P","accountActive":1} – dereck Jun 20 '14 at 03:07

1 Answers1

3

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)

Community
  • 1
  • 1
JensG
  • 13,148
  • 4
  • 45
  • 55