douxian1895 2016-07-29 05:50
浏览 158
已采纳

进行JSON命名策略

I am very new in Go and I was exploring go to use for one of my micro services. I was wonder the way Go converts objects to Json and back to Json. But unfortunately i found configuring the output field names are little difficult with the use of tag names.

type MyStruct strust{
   MyName string
}

will converts to json

{
    "MyName" : "somestring"
}

But we are following a naming strategy for the whole api across Organization to follow snake_case

{
        "my_name" : "somestring"
}

Is considered to be valid in my org.

I started using the tags like json:"my_name,omitempty" etc per field level.

I would like to know is there a way i can configure it at global project level, so that i dont want to take care this at every object and its field level.

  • 写回答

1条回答 默认 最新

  • dscw1223 2016-07-29 07:24
    关注

    You could try something like this: https://play.golang.org/p/i5X69ywjup

    Core functionality:

    // SnakeCaseEncode snake_case's the given struct's field names.
    func SnakeCaseEncode(i interface{}) map[string]interface{} {
        rt, rv := reflect.TypeOf(i), reflect.ValueOf(i)
    
        if rt.Kind() == reflect.Ptr {
            i := reflect.Indirect(rv).Interface()
            rt, rv = reflect.TypeOf(i), reflect.ValueOf(i)
        }
    
        out := make(map[string]interface{}, rt.NumField())
    
        for i := 0; i < rt.NumField(); i++ {
            if strings.Contains(rt.Field(i).Tag.Get("json"), "omitempty") {
                continue
            }
    
            k := snakeCase(rt.Field(i).Name)
    
            out[k] = rv.Field(i).Interface()
        }
    
        return out
    }
    
    // snakeCase provides basic ASCII conversion of camelCase field names to snake_case.
    func snakeCase(s string) string {
        out := make([]rune, 0, utf8.RuneCountInString(s))
    
        for i, r := range s {
            if r >= 'A' && r <= 'Z' {
                r += 32
    
                if i > 0 {
                    out = append(out, '_')
                }
            }
    
            out = append(out, r)
        }
    
        return string(out)
    }
    

    To support map, slice etc. you'll have to expand on this simple version.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输