Convert an object to a JSON string with thrift json serialization

Shashika picture Shashika · Feb 6, 2014 · Viewed 17.6k times · Source

I'm new to the thrift. I need to convert my data object to a JSON string with Thrift JSON serialization.

I tried in this way.

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

In here is an error, that object_name should be in TBase. How can I resolve this ?

Answer

JensG picture JensG · Feb 6, 2014

In here is an error, that object_name should be in TBase.

Next time, please post the exact error message (use copy+paste), this makes it easier for all of us.

How can I resolve this?

Whatever you want to serialize with Thrift, must be an descendant of Thrift's TBase class. You achieve this by writing some Thrift IDL and save it as a file (e.g. MyDataStructs.thrift):

struct Employee {
    1: string name
    2: string surname
    3: i32 age
}

Next, you pass that file to the Thrift compiler and tell him to generate some C# code from it:

thrift  -gen csharp  MyDataStructs.thrift

This gives you a class derived from TBase:

public partial class Employee : TBase
{
  private string _name;
  private string _surname;
  private int _age;

  // properties
  public string Name {... }
  public string Surname  { ... }
  public int Age  { ... }

  // some details omitted

  public void Read (TProtocol iprot)
  {
    // generated code for Read() method
  }

  public void Write(TProtocol oprot) {
    // generated code for Write() method
  }

  public override string ToString() {
    // generated code for ToString() method
  }

}

This is what Thrift expects.