douwei1904 2018-05-05 08:22
浏览 61
已采纳

元数据/非元数据int类型

I use an int type to represent an enum. I want to convert it to string when I marshal it to JSON, AFAIK, I should implement UnmarshalJSON and MarshalJSON, but it complains:

marshal error: json: error calling MarshalJSON for type main.trxStatus: invalid character 'b' looking for beginning of valueunexpected end of JSON input

when marshalling. Then I've add the quotes to the marshalled string:

func (s trxStatus) MarshalJSON() ([]byte, error) {
    return []byte("\"" + s.String() + "\""), nil
}

the Marshal works now but it can't Unmarshal from the marshalled byte stream correctly.

package main

import (
    "encoding/json"
    "fmt"
)

type trxStatus int

type test struct {
    S trxStatus
    A string
}

const (
    buySubmitted trxStatus = iota
    buyFilled
    sellSubmiited
    sellFilled
    finished
)

var ss = [...]string{"buySubmitted", "buyFilled", "sellSubmiited", "sellFilled", "Finished"}

func (s *trxStatus) UnmarshalJSON(bytes []byte) error {
    status := string(bytes)
    // unknown
    for i, v := range ss {
        if v == status {
            tttt := trxStatus(i)
            *s = tttt
            break
        }
    }
    return nil
}

func (s trxStatus) MarshalJSON() ([]byte, error) {
    return []byte(s.String()), nil
}

func (s trxStatus) String() string {

    if s < buySubmitted || s > finished {
        return "Unknown"
    }

    return ss[s]
}

func main() {
    s := test{S: buyFilled, A: "hello"}
    j, err := json.Marshal(s)
    if err != nil {
        fmt.Printf("marshal error: %v", err)
    }
    var tt test
    fmt.Println(json.Unmarshal(j, &tt))
    fmt.Println(tt)
}
  • 写回答

1条回答 默认 最新

  • dpzbzp8728 2018-05-05 09:01
    关注

    When writing your custom Marshaler and Unmarshaler implementations make sure to include or trim the surrounding double quotes of json strings.

    func (s *trxStatus) UnmarshalJSON(bytes []byte) error {
        status := string(bytes)
        if n := len(status); n > 1 && status[0] == '"' && status[n-1] == '"' {
            status = status[1:n-1] // trim surrounding quotes
        }
        // unknown
        for i, v := range ss {
            if v == status {
                tttt := trxStatus(i)
                *s = tttt
                break
            }
        }
        return nil
    }
    
    func (s trxStatus) MarshalJSON() ([]byte, error) {
        return []byte(`"` + s.String() + `"`), nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站