doupo2241 2017-08-30 06:22
浏览 12
已采纳

将ins切片到字符串行

I have a struct as this:

type Int64Slice []int64
type DataWrapper struct {
    ListId Int64Slice    `json:"listid" required`
    Domain string `json:"domain" required`
    Name   string `json:"name,omitempty"`
}

And I need it become:

{
    "listid": "1 2 3 4 5",
    "domain": "mydomain"
}

I have wrote custom MarshalJSON:

func (u Int64Slice) MarshalJSON() ([]byte, error) {
    var result string
    if u == nil {
        result = "null"
    } else {
        result = strings.Trim(strings.Join(strings.Fields(fmt.Sprint(u)), " "), "[]")
        Logger.Debugln(result)
    }
    return []byte(result), nil
}

func (d *DataWrapper) ToJSON() []byte {
    result, err := json.Marshal(d)
    if err != nil {
        log.Fatalln(err)
        panic(err)
    }
    return result
}

At the line Logger.Debugln(result), it prints this result:

20170830090317506 20170830090026319 20170830111023194 201708301043081 ...

json: error calling MarshalJSON for type models.Int64Slice: invalid character '2' after top-level value

  • 写回答

2条回答 默认 最新

  • dongpengqin3898 2017-08-30 07:35
    关注

    I think you have it backwards. Use the bytes.Buffer type to incrementally build up the string representation of your data.

    The program

    package main
    
    import (
        "bytes"
        "encoding/json"
        "os"
        "strconv"
    )
    
    type Int64Slice []int64
    
    func (s Int64Slice) MarshalJSON() ([]byte, error) {
        if s == nil {
            return []byte("null"), nil
        }
    
        var b bytes.Buffer
        b.WriteByte('"')
        for i, v := range s {
            if i > 0 {
                b.WriteByte('\x20')
            }
            b.WriteString(strconv.FormatInt(v, 10))
        }
    
        b.WriteByte('"')
        return b.Bytes(), nil
    }
    
    func main() {
        var (
            a Int64Slice = nil
            b = Int64Slice{
                42,
                12,
                0,
            }
        )
        enc := json.NewEncoder(os.Stdout)
        enc.Encode(a)
        enc.Encode(b)
    }
    

    Prints:

    null
    "42 12 0"
    

    Playground link.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?