使用节俭的json序列化将对象转换为JSON字符串 [英] Convert an object to a JSON string with thrift json serialization

查看:84
本文介绍了使用节俭的json序列化将对象转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我以此方式尝试过.

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

在这里是一个错误,object_name应该在TBase中.我该如何解决?

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

推荐答案

这是一个错误,该object_name应该在TBase中.

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?

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

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
}

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

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

thrift  -gen csharp  MyDataStructs.thrift

这为您提供了一个从TBase派生的类:

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
  }

}

这是Thrift的期望.

This is what Thrift expects.

这篇关于使用节俭的json序列化将对象转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆