dongmeng9048 2018-03-21 20:02
浏览 977

Golang:JSON:如何将字符串数组解组为[] 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"`

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:

  • 写回答

2条回答 默认 最新

  • dongluan7821 2018-03-21 20:09
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型