将整数切片转换为字符串行

huangapple go评论74阅读模式
英文:

Marshal int slice to string line

问题

我有一个这样的结构体:

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

我希望它变成这样:

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

我已经编写了自定义的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
}

Logger.Debugln(result)这一行,它打印出了这个结果:

20170830090317506 20170830090026319 20170830111023194 201708301043081 ...

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

英文:

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

答案1

得分: 2

我认为你弄反了。
使用bytes.Buffer类型逐步构建数据的字符串表示。

程序如下:

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

输出结果为:

null
"42 12 0"

Playground链接

英文:

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.

答案2

得分: 2

20170830090317506 20170830090026319 20170830111023194 201708301043081 不是一个有效的 JSON 值。它被解释为一个有效的数字 (20170830090317506),后面跟着一个有效的空格,然后是以 2 字符开头的无效数据;因此你观察到的错误。

它需要加上引号:

尝试像这样:

result = `"` + strings.Trim(strings.Join(strings.Fields(fmt.Sprint(u)), " "), "[]") + `"`
英文:

20170830090317506 20170830090026319 20170830111023194 201708301043081 is not a valid JSON value. It is interpreted as a valid number (20170830090317506) followed by a valid space, followed by invalid data, beginning with the 2 character; thus the error you observed.

It needs quotes around it:

Try something like:

result = `"` + strings.Trim(strings.Join(strings.Fields(fmt.Sprint(u)), " "), "[]") + `"`

huangapple
  • 本文由 发表于 2017年8月30日 14:22:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/45953307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定