Go語言json編碼駝峰轉下劃線、下劃線轉駝峰

一、需求

golang默認的結構體json轉碼出來,都是根據欄位名生成的大寫駝峰格式,但是一般我們最常用的json格式是小寫駝峰或者小寫下劃線,因此,我非常需要一個統一的方法去轉換,而不想挨個寫json標籤,例如

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	type Person struct {
		HelloWold       string
		LightWeightBaby string
	}
	var a = Person{HelloWold: "chenqionghe", LightWeightBaby: "muscle"}
	res, _ := json.Marshal(a)
	fmt.Printf("%s", res)
}

運行結果

{"HelloWold":"chenqionghe","LightWeightBaby":"muscle"}

輸出來的json結構是大寫駝峰的,肯定非常彆扭的,當然 ,我們通過設定json標籤來設定輸出的json欄位名,例如

type Person struct {
	HelloWold       string `json:"hello_wold"`
	LightWeightBaby string `json:"light_weight_baby"`
}

但是如果欄位特別多,需要挨個設置也太麻煩了。

二、實現

Golang 的標準 Json 在處理各種數據類型是都是調用其類型介面UnmarshalJSON解碼和MarshalJSON編碼進行轉換的,我們只要實現了“
所以我們可以封裝一個統一轉換下劃線的json結構體或統一轉換駝峰的json結構體,並實現MarshalJSON方法,就可以達到目的。
實現如下

package jsonconv

import (
	"bytes"
	"encoding/json"
	"log"
	"regexp"
	"strconv"
	"strings"
	"unicode"
)

/*************************************** 下劃線json ***************************************/
type JsonSnakeCase struct {
	Value interface{}
}

func (c JsonSnakeCase) MarshalJSON() ([]byte, error) {
	// Regexp definitions
	var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`)
	var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`)
	marshalled, err := json.Marshal(c.Value)
	converted := keyMatchRegex.ReplaceAllFunc(
		marshalled,
		func(match []byte) []byte {
			return bytes.ToLower(wordBarrierRegex.ReplaceAll(
				match,
				[]byte(`${1}_${2}`),
			))
		},
	)
	return converted, err
}

/*************************************** 駝峰json ***************************************/
type JsonCamelCase struct {
	Value interface{}
}

func (c JsonCamelCase) MarshalJSON() ([]byte, error) {
	var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`)
	marshalled, err := json.Marshal(c.Value)
	converted := keyMatchRegex.ReplaceAllFunc(
		marshalled,
		func(match []byte) []byte {
			matchStr := string(match)
			key := matchStr[1 : len(matchStr)-2]
			resKey := Lcfirst(Case2Camel(key))
			return []byte(`"` + resKey + `":`)
		},
	)
	return converted, err
}

/*************************************** 其他方法 ***************************************/
// 駝峰式寫法轉為下劃線寫法
func Camel2Case(name string) string {
	buffer := NewBuffer()
	for i, r := range name {
		if unicode.IsUpper(r) {
			if i != 0 {
				buffer.Append('_')
			}
			buffer.Append(unicode.ToLower(r))
		} else {
			buffer.Append(r)
		}
	}
	return buffer.String()
}

// 下劃線寫法轉為駝峰寫法
func Case2Camel(name string) string {
	name = strings.Replace(name, "_", " ", -1)
	name = strings.Title(name)
	return strings.Replace(name, " ", "", -1)
}

// 首字母大寫
func Ucfirst(str string) string {
	for i, v := range str {
		return string(unicode.ToUpper(v)) + str[i+1:]
	}
	return ""
}

// 首字母小寫
func Lcfirst(str string) string {
	for i, v := range str {
		return string(unicode.ToLower(v)) + str[i+1:]
	}
	return ""
}

// 內嵌bytes.Buffer,支援連寫
type Buffer struct {
	*bytes.Buffer
}

func NewBuffer() *Buffer {
	return &Buffer{Buffer: new(bytes.Buffer)}
}

func (b *Buffer) Append(i interface{}) *Buffer {
	switch val := i.(type) {
	case int:
		b.append(strconv.Itoa(val))
	case int64:
		b.append(strconv.FormatInt(val, 10))
	case uint:
		b.append(strconv.FormatUint(uint64(val), 10))
	case uint64:
		b.append(strconv.FormatUint(val, 10))
	case string:
		b.append(val)
	case []byte:
		b.Write(val)
	case rune:
		b.WriteRune(val)
	}
	return b
}

func (b *Buffer) append(s string) *Buffer {
	defer func() {
		if err := recover(); err != nil {
			log.Println("*****記憶體不夠了!******")
		}
	}()
	b.WriteString(s)
	return b
}

三、使用

JsonSnakeCase統一轉下劃線json

使用jsonconv.JsonSnakeCase包裹一下要輸出json的對象即可

func main() {
	type Person struct {
		HelloWold       string
		LightWeightBaby string
	}
	var a = Person{HelloWold: "chenqionghe", LightWeightBaby: "muscle"}
	res, _ := json.Marshal(jsonconv.JsonSnakeCase{a})
	fmt.Printf("%s", res)
}

輸出如下

{"hello_wold":"chenqionghe","light_weight_baby":"muscle"}

JsonSnakeCase統一轉駝峰json

已經指定了下劃線標籤的結構體,我們也可以統一轉為駝峰的json

func main() {
	type Person struct {
		HelloWold       string `json:"hello_wold"`
		LightWeightBaby string `json:"light_weight_baby"`
	}
	var a = Person{HelloWold: "chenqionghe", LightWeightBaby: "muscle"}
	res, _ := json.Marshal(jsonconv.JsonCamelCase{a})
	fmt.Printf("%s", res)
}

輸出如下

{"helloWold":"chenqionghe","lightWeightBaby":"muscle"}

非常方便的解決了json統一轉碼格式的需求

Tags: