Java 使用 thrift json 序列化将对象转换为 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21597271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an object to a JSON string with thrift json serialization
提问by Shashika
I'm new to the thrift. I need to convert my data object to a JSON string
with Thrift JSON
serialization.
我是节俭的新手。我需要将我的数据对象转换为JSON string
带有Thrift JSON
序列化的对象。
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 ?
这里有一个错误,object_name
应该在TBase
. 我该如何解决这个问题?
采纳答案by JensG
In here is an error, that object_name should be in TBase.
这里有一个错误,object_name 应该在 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 IDLand save it as a file (e.g. MyDataStructs.thrift
):
无论你想用 Thrift 序列化什么,都必须是 ThriftTBase
类的后代。您可以通过编写一些Thrift IDL并将其保存为文件(例如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 编译器,并告诉他从中生成一些 C# 代码:
thrift -gen csharp MyDataStructs.thrift
This gives you a class derived from TBase:
这为您提供了一个从 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.
这是 Thrift 所期望的。
回答by A Paul
If below is what your are doing then it should work. Check if you are doing this. Employee is a demo call here, you have to use your actual class.
如果下面是您正在做的事情,那么它应该可以工作。检查您是否正在执行此操作。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);