【问题标题】:Convert an object to a JSON string with thrift json serialization使用 thrift json 序列化将对象转换为 JSON 字符串
【发布时间】:2014-03-03 01:34:50
【问题描述】:

我是新手。我需要使用Thrift JSON 序列化将我的数据对象转换为JSON string

我试过这种方式。

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

这里有一个错误,object_name 应该在 TBase 中。我该如何解决这个问题?

【问题讨论】:

  • 只能序列化thrift中定义的struct类型的对象。

标签: java json thrift thrift-protocol


【解决方案1】:

这里有一个错误,object_name 应该在 TBase 中。

下一次,请发布确切的错误消息(使用复制+粘贴),这样对我们所有人来说都更容易。

我该如何解决这个问题?

无论你想用 Thrift 序列化什么,都必须是 Thrift 的 TBase 类的后代。您可以通过编写一些Thrift IDL 并将其保存为文件(例如MyDataStructs.thrift)来实现:

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

接下来,将该文件传递给 Thrift 编译器并告诉他从中生成一些 C# 代码:

thrift  -gen csharp  MyDataStructs.thrift

这为您提供了一个从 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
  }

}

这正是 Thrift 所期望的。

【讨论】:

    【解决方案2】:

    如果您正在执行以下操作,那么它应该可以工作。检查你是否正在这样做。 Employee 在这里是一个演示调用,你必须使用你的实际类。

    Employee object_name= new Employee();
    object_name.setAge(27);
    object_name.setName("Test");
    
    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
    String json = serializer.toString(object_name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 2020-05-27
      • 1970-01-01
      • 2018-05-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多