Golang:JSON:如何将字符串数组解组为[] int64 [英] Golang: JSON: How do I unmarshal array of strings into []int64

查看:124
本文介绍了Golang:JSON:如何将字符串数组解组为[] int64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Golang encoding/json包使您可以使用,string struct标记来将字符串值(如"309230")编组/解编为int64字段.示例:

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"`

但是,这不适用于切片,即. []int64:

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

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

是否可以将JSON字符串数组编组/解编为[] int64字段?

https://golang.org/pkg/encoding/json 的引用:

字符串"选项表示字段在JSON编码的字符串中存储为JSON.它仅适用于字符串,浮点数,整数或布尔类型的字段.在与JavaScript程序通信时,有时会使用这种额外的编码级别:

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:

推荐答案

对于感兴趣的人,我发现了使用自定义类型定义了MarshalJSON()UnmarshalJSON()方法的解决方案.

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
}

上述解决方案将[]int64编组为JSON字符串数组.取消编组可以从JSON字符串和整数数组进行,即:

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

请参见 https://play.golang.org/p/BOqUBGR3DXm

这篇关于Golang:JSON:如何将字符串数组解组为[] int64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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