元数据/非元数据int类型 [英] Marshal/Unmarshal int type

查看:132
本文介绍了元数据/非元数据int类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用int类型表示一个枚举.当我将其编组为JSON,AFAIK时,我想将其转换为字符串,我应该实现UnmarshalJSONMarshalJSON,但是它抱怨:

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:

元帅错误:json:调用MarshalJSON作为类型时出错 main.trxStatus:无效字符"b"正在寻找 JSON输入的值意外结束

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
}

Marshal现在可以工作,但是无法正确地从编组的字节流中Unmarshal.

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

推荐答案

在编写自定义的Marshaler和Unmarshaler实现时,请确保包括或修剪json字符串的双引号.

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
}

这篇关于元数据/非元数据int类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆