登录
首页 >  Golang >  Go问答

Golang: JSON: How do I unmarshal array of strings into []int64

来源:Golang技术栈

时间:2023-03-24 14:27:58 148浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Golang: JSON: How do I unmarshal array of strings into []int64》,主要内容是讲解golang等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

Golang encoding/json package lets you use ,string struct tag in order to marshal/unmarshal string values (like "309230") into int64 field. Example:

Int64String int64 `json:",string"`

However, this doesn't work for slices, ie. []int64:

Int64Slice []int64 `json:",string"` // Doesn't work.

Is there any way to marshal/unmarshal JSON string arrays into []int64 field?


Quote from https://golang.org/pkg/encoding/json:

The "string" option signals that a field is stored as JSON inside a JSON- encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

正确答案

For anyone interested, I found a solution using a custom type having MarshalJSON() and UnmarshalJSON() methods defined.

type Int64StringSlice []int64

func (slice Int64StringSlice) MarshalJSON() ([]byte, error) {
    values := make([]string, len(slice))
    for i, value := range []int64(slice) {
        values[i] = fmt.Sprintf(`"%v"`, value)
    }

    return []byte(fmt.Sprintf("[%v]", strings.Join(values, ","))), nil
}

func (slice *Int64StringSlice) UnmarshalJSON(b []byte) error {
    // Try array of strings first.
    var values []string
    err := json.Unmarshal(b, &values)
    if err != nil {
        // Fall back to array of integers:
        var values []int64
        if err := json.Unmarshal(b, &values); err != nil {
            return err
        }
        *slice = values
        return nil
    }
    *slice = make([]int64, len(values))
    for i, value := range values {
        value, err := strconv.ParseInt(value, 10, 64)
        if err != nil {
            return err
        }
        (*slice)[i] = value
    }
    return nil
}

The above solution marshals []int64 into JSON string array. Unmarshaling works from both JSON string and integer arrays, ie.:

{"bars": ["1729382256910270462", "309286902808622", "23"]}

{"bars": [1729382256910270462, 309286902808622, 23]}

See example at https://play.golang.org/p/BOqUBGR3DXm

理论要掌握,实操不能落!以上关于《Golang: JSON: How do I unmarshal array of strings into []int64》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>