dongxie45083 2016-08-12 13:01
浏览 63

如何在Golang中使用数字枚举以用户友好的JSON格式保存节俭结构?

Task.thrift (Thrift version 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,
}

Generated Apache Thrift code for Java marshal enums by numbers.

$ thrift -r --gen java Task.thrift

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

How to generate Apache Thrift code for Golang with JSON marshal enum by number instead of name?

$ thrift -r --gen go Task.thrift

This example make enums by strings:

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

This example make enums by numbers, but add two extra numbers in any list of 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)
  • 写回答

2条回答 默认 最新

  • douchang8758 2016-08-12 18:48
    关注

    Use the TJSONProtocol instead, this provides you with an interchangeable, JSON-based data format.

    The 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.

    Other than that, if TSimpleJSONProtocol produces different output for Java and Go, you may have found an inconsistency and consider filing a JIRA ticket including a suitable test case.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类