dqpkea9486 2018-08-05 15:16
浏览 114
已采纳

封送至JSON时将类型int转换为const名称的字符串

I have a struct that looks like this:

type Type int

const (
    A Type = iota
    B
    C
)

type Character struct {
    Type Type   `json:"type"`
}

When I call json.Marshal(...) on the struct, is there a way that the json:"type" representation is a string called either "A", "B", or "C"?

When this is presented in JSON, nobody is going to know what 0, 1, or 2 is, so the name of the constant is more useful.

Apologies if this has been asked before. I googled all over and couldn't find anything.

Here is an example:

type Type int

const (
    A Type = iota
    B
    C
)

type Character struct {
    Type Type   `json:"type,string"`
}

func main() {
    c := Character{}
    c.Type = A
    j, err := json.Marshal(c)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(j))
}

I want fmt.Println(string(j)) to print {"type":"A"}, not {"type":0}.

  • 写回答

3条回答 默认 最新

  • duanquan4451 2018-08-05 18:06
    关注

    You need to define a custom marshaller for your type.

    type Type int
    
    const (
        A Type = iota
        B
        C
    )
    
    var typeToString = map[Type]string{
        A: "A",
        B: "B",
        C: "C",
    }
    
    func (t Type) MarshalJSON() ([]byte, error) {
        return json.Marshal(typeToString[t])
    }
    
    type Character struct {
        Type Type `json:"type"`
    }
    
    func main() {
        c := Character{}
        c.Type = A
        j, err := json.Marshal(c)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(j))
    }
    

    The function MarshalJSON defines how json.Marshal should marshal your type. You can do something similar for unmarshaling if you need to go the other direction as well.

    See https://play.golang.org/p/mLxThWA19by.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大