Differences between revisions 4 and 5
Revision 4 as of 2009-09-20 23:47:13
Size: 1785
Editor: localhost
Comment: converted to 1.6 markup
Revision 5 as of 2009-10-30 17:26:10
Size: 1765
Comment:
Deletions are marked like this. Additions are marked like this.
Line 8: Line 8:
import com.facebook.thrift.TBase;
import com.facebook.thrift.TException;
import com.facebook.thrift.TSerializer;
import com.facebook.thrift.TDeserializer;
import com.facebook.thrift.protocol.TBinaryProtocol;
import com.facebook.thrift.protocol.TProtocol;
import com.facebook.thrift.protocol.TProtocolFactory;
import com.facebook.thrift.protocol.TSimpleJSONProtocol;
import com.facebook.thrift.transport.TIOStreamTransport;
import com.facebook.thrift.transport.TTransport;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TTransport;

Assuming you're using the definitions in "tutorial.thrift":

Importing the Classes

You may not need all of these.

import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TTransport;

import tutorial.Work;
import tutorial.Operation;
import tutorial.Constants;

Creating Objects, Using Constants

Work work = new Work();
work.num1 = 7;
work.num2 = 9;
work.op = Operation.ADD;

Or, if you used the "beans" option to generate ThriftJavaBeans code:

Work work = new Work();
work.setNum1(7);
work.setNum2(9);
work.setOp(Operation.ADD);

Serializing to/from a Byte Array

TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
byte[] bytes = serializer.serialize(work);

TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
Work moreWork = new Work();
deserializer.deserialize(moreWork, bytes);

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. Using the object created above, the "Simple" JSON string is:

{"num1":7,"num2":9,"op":1}

ThriftUsageJava (last edited 2009-10-30 17:26:10 by EsteveFernandez)