濮阳杆衣贸易有限公司

主頁 > 知識(shí)庫 > Go語言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)

Go語言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)

熱門標(biāo)簽:澳門防封電銷卡 廣東語音外呼系統(tǒng)供應(yīng)商 福州鐵通自動(dòng)外呼系統(tǒng) 智能電銷機(jī)器人營銷 濮陽自動(dòng)外呼系統(tǒng)代理 地圖標(biāo)注測(cè)試 烏魯木齊人工電銷機(jī)器人系統(tǒng) 賺地圖標(biāo)注的錢犯法嗎 長沙ai機(jī)器人電銷

一、需求

golang默認(rèn)的結(jié)構(gòu)體json轉(zhuǎn)碼出來,都是根據(jù)字段名生成的大寫駝峰格式,但是一般我們最常用的json格式是小寫駝峰或者小寫下劃線,因此,我們非常需要一個(gè)統(tǒng)一的方法去轉(zhuǎn)換,而不想挨個(gè)寫json標(biāo)簽,例如

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)
}

運(yùn)行結(jié)果

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

輸出來的json結(jié)構(gòu)是大寫駝峰的,肯定非常別扭的,當(dāng)然 ,我們通過設(shè)定json標(biāo)簽來設(shè)定輸出的json字段名,例如

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

但是如果字段特別多,需要挨個(gè)設(shè)置也太麻煩了。

二、實(shí)現(xiàn)

Golang 的標(biāo)準(zhǔn) Json 在處理各種數(shù)據(jù)類型是都是調(diào)用其類型接口UnmarshalJSON解碼和MarshalJSON編碼進(jìn)行轉(zhuǎn)換的,所以我們可以封裝一個(gè)統(tǒng)一轉(zhuǎn)換下劃線的json結(jié)構(gòu)體或統(tǒng)一轉(zhuǎn)換駝峰的json結(jié)構(gòu)體,并實(shí)現(xiàn)MarshalJSON方法,就可以達(dá)到目的。

實(shí)現(xiàn)如下

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
}

/*************************************** 其他方法 ***************************************/
// 駝峰式寫法轉(zhuǎn)為下劃線寫法
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()
}

// 下劃線寫法轉(zhuǎn)為駝峰寫法
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 ""
}

// 內(nèi)嵌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("*****內(nèi)存不夠了!******")
 }
 }()
 b.WriteString(s)
 return b
}

三、使用

JsonSnakeCase統(tǒng)一轉(zhuǎn)下劃線json

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

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"}

JsonCamelCase統(tǒng)一轉(zhuǎn)駝峰json

已經(jīng)指定了下劃線標(biāo)簽的結(jié)構(gòu)體,我們也可以統(tǒng)一轉(zhuǎn)為駝峰的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統(tǒng)一轉(zhuǎn)碼格式的需求

到此這篇關(guān)于Go語言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Go 駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • js對(duì)象屬性名駝峰式轉(zhuǎn)下劃線的實(shí)例代碼
  • js下劃線和駝峰互相轉(zhuǎn)換的實(shí)現(xiàn)(多種方法)

標(biāo)簽:廣西 調(diào)研邀請(qǐng) 德州 西雙版納 慶陽 阿克蘇 太原 貴陽

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Go語言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)》,本文關(guān)鍵詞  語言,json,編碼,駝峰,轉(zhuǎn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Go語言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)》相關(guān)的同類信息!
  • 本頁收集關(guān)于Go語言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    武义县| 通道| 南木林县| 蒙城县| 德兴市| 陆丰市| 永兴县| 汤阴县| 临湘市| 泰宁县| 普洱| 饶平县| 颍上县| 布拖县| 曲沃县| 老河口市| 沁水县| 临高县| 紫阳县| 虹口区| 张家界市| 微山县| 兴仁县| 公主岭市| 秭归县| 马关县| 金阳县| 桐梓县| 贺州市| 耒阳市| 孟州市| 淮北市| 收藏| 永登县| 民权县| 托克托县| 张掖市| 石渠县| 五常市| 开江县| 察哈|