如何在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)

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.

Remove this commit and re-make thrift-0.9.3 then use json.Marshal/Unmarshal.