6

golang json 编解码枚举字段映射包 - jsonmap

 8 months ago
source link: https://studygolang.com/articles/36294
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

golang json 编解码枚举字段映射包 - jsonmap

cg33 · 5天之前 · 469 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

从数据源查出来到结构体,还需要映射返回输出,不想那么麻烦。试试这个包:

https://github.com/chenhg5/jsonmap

只需要在结构体的tag声明即可:

package main

import (
    "encoding/json"
    "fmt"

    "github.com/chenhg5/jsonmap"
)

func main() {

    var text = `{
        "type": "cow"
    }`

    type Animal struct {
        Type uint8 `json:"type" jsonmap:"0:dog;1:cat;2:cow;3:others"`
    }

    var animal = new(Animal)
    _ = json.Unmarshal([]byte(text), jsonmap.Wrap(animal))
    fmt.Printf("%+v\n", animal)

    // &Animal{Type: 2}

    res, _ := json.MarshalIndent(jsonmap.Wrap(animal), "", "    ")
    fmt.Println(string(res))

    // {"type": "cow"}
}

dddd.


有疑问加站长微信联系(非本文作者))

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK