【问题标题】:How to save thrift struct in a user friendly JSON format with enums by numbers in Golang?如何在 Golang 中使用数字枚举以用户友好的 JSON 格式保存节俭结构?
【发布时间】:2016-08-15 20:40:45
【问题描述】:

Task.thrift (Thrift 版本 0.9.3)

enum AttributeApp {
  a = 1,
  b = 2,
  c = 3
}

typedef i32 attrTypeId

struct Task {
  1: required attrTypeId type_id,
  2: required list<AttributeApp> app_to,
}

为 Java 编组枚举生成 Apache Thrift 代码。

$ thrift -r --gen java Task.thrift

TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(task);
Util.writeLog("task.json", json);

如何使用 JSON 编组枚举按数字而不是名称为 Golang 生成 Apache Thrift 代码?

$ thrift -r --gen go Task.thrift

这个例子通过字符串创建枚举:

bt, err := json.Marshal(task)
if err != nil {
    return err
}
err = ioutil.WriteFile("task.json", bt, 0666)

这个例子用数字创建枚举,但是在任何 json 列表中添加两个额外的数字:

transport := thrift.NewTMemoryBufferLen(1024)
protocol := thrift.NewTSimpleJSONProtocolFactory().GetProtocol(transport)
ts := &thrift.TSerializer{transport, protocol}
bt, err := ts.Write(task)
if err != nil {
    return err
}
err = ioutil.WriteFile("task.json", bt, 0666)

【问题讨论】:

    标签: go enums code-generation marshalling thrift


    【解决方案1】:

    请改用TJSONProtocol,这为您提供了一种可互换的、基于 JSON 的数据格式。

    TSimpleJSONProtocol is not intended to be used as a serialization format, at least not when you plan to read it back into your program using Thrift。

    除此之外,如果 TSimpleJSONProtocol 为 Java 和 Go 生成不同的输出,您可能已经发现不一致并考虑提交包含合适测试用例的 JIRA 票证。

    【讨论】:

    • 对用户友好的 JSON 格式的序列化感兴趣。 TJSONProtocol 工作正常,但对用户不友好。
    【解决方案2】:

    删除 this 提交并重新制作 thrift-0.9.3 然后使用 json.Marshal/Unmarshal。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 2016-08-19
      相关资源
      最近更新 更多