gpt4 book ai didi

java - Thrift - 从简单的 JSON 转换

转载 作者:搜寻专家 更新时间:2023-10-31 19:55:38 27 4
gpt4 key购买 nike

我创建了以下 Thrift 对象:

struct Student{
1: string id;
2: string firstName;
3: string lastName
}

现在我想从 JSON 中读取这个对象。根据这个post这是可能的

所以我写了下面的代码:

String json = "{\"id\":\"aaa\",\"firstName\":\"Danny\",\"lastName\":\"Lesnik\"}";
StudentThriftObject s = new StudentThriftObject();
byte[] jsonAsByte = json.getBytes("UTF-8");
TMemoryBuffer memBuffer = new TMemoryBuffer(jsonAsByte.length);
memBuffer.write(jsonAsByte);

TProtocol proto = new TJSONProtocol(memBuffer);
s.read(proto);

我得到的是以下异常:

Exception in thread "main" org.apache.thrift.protocol.TProtocolException: Unexpected character:i
at org.apache.thrift.protocol.TJSONProtocol.readJSONSyntaxChar(TJSONProtocol.java:322)
at org.apache.thrift.protocol.TJSONProtocol.readJSONInteger(TJSONProtocol.java:698)
at org.apache.thrift.protocol.TJSONProtocol.readFieldBegin(TJSONProtocol.java:837)
at com.vanilla.thrift.example.entities.StudentThriftObject$StudentThriftObjectStandardScheme.read(StudentThriftObject.java:486)
at com.vanilla.thrift.example.entities.StudentThriftObject$StudentThriftObjectStandardScheme.read(StudentThriftObject.java:479)
at com.vanilla.thrift.example.entities.StudentThriftObject.read(StudentThriftObject.java:413)
at com.vanilla.thrift.controller.Main.main(Main.java:24)

我错过了什么吗?

最佳答案

您忽略了一个事实,即 Thrift 的 JSON 与您的不同。未写入字段名称,而是写入(和预期的)分配的字段 ID 号。下面是 Thrift 的 JSON 协议(protocol)示例:

[1,"MyService",2,1,{"1":{"rec":{"1":{"str":"Error: Process() failed"}}}}]

换句话说,Thrift 不打算解析任何 类型的 JSON。它支持一种非常具体的 JSON 格式作为可能的传输方式之一。

但是,根据您的 JSON 数据的来源,如果您能够在双方都使用 Thrift,Thrift 可能仍然可以帮助您。在这种情况下,编写一个 IDL 来描述数据结构,将其提供给 Thrift 编译器,并将生成的代码和库的必要部分与您的项目集成。

如果 JSON 的来源超出您的范围,或者如果由于某种原因无法更改 JSON 格式,您需要寻找其他方法。

格式和语义是不同的野兽

在某种程度上,整个问题可以与 XML 进行比较:有一种通用的 XML 语法,它告诉我们如何格式化事物,以便任何符合标准的 XML 处理器都可以读取它们。

但是如果我们从某人那里得到某个 XML 文件,那么了解 XML 的规则只是答案的一半。即使我们的 XML 解析器可以成功读取文件,因为它是格式良好的 XML,我们需要知道数据的语义才能真正利用该文件中的内容:它是 customer data record 吗? ?还是 SOAP envelope ?也许是 configuration file

这就是 DTD 或 XML 模式发挥作用的地方,它们的存在是为了描述 XML 数据的内容。如果不知道逻辑结构,您就会迷路,因为在 XML 中有无数种可能的表达方式。与 JSON 完全相同,除了 JSON schema descriptions。不太常用。

所以你的意思是,我们只需要一种方法来告诉 Thrift JSON 是如何组织的?

不,因为 Thrift 背后的目的和想法是拥有一个框架来尽可能高效地反序列化事物和/或实现 RPC 服务器和客户端。它不打算有一个通用的文件解析器。相反,Thrift 只读和说它自己的一组格式,即 plugged into the architecture as protocols :Thrift Binary、Thrift JSON、Thrift Compact 等等。

您可以做什么:除了我在回答的第一部分中所说的以外,您还可以考虑编写自己的自定义 Thrift 协议(protocol)实现以支持您选择的特定 JSON 格式。这并不难,值得一试。

关于java - Thrift - 从简单的 JSON 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20261519/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com