自定义golang sql.NULL*类型的MarshalText()方法

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

custom MarshalText() for golang sql.NULL* types

问题

我正在尝试在使用SQL.NullFloat64和https://github.com/kisielk/sqlstruct包的代码中将SQL结果转换为JSON。

问题是我在JSON中得到了以下结果,而不仅仅是值:

{
"Float64": 141,
"Valid": true
}

根据上述github问题中的建议,我尝试创建一个自定义的MarshalText()函数,但它从未被调用。

代码在这里:https://gist.github.com/fils/3f557941d71f1a7165ca

生成的JSON在这里:https://gist.github.com/fils/a01cadcbb5dc7c797c3e

CSV转储函数可以正确获取和输出值,但不确定如何在JSON中实现相同的效果。

无论是使用sql.NullFloat64还是自定义类型NullFloat64,结果都是相同的。

英文:

I am trying to marshal SQL results into JSON in code that is using SQL.NullFloat64 and the https://github.com/kisielk/sqlstruct package.

Ref: https://github.com/kisielk/sqlstruct/issues/11#issuecomment-143400458

This issue is I am getting the

{
    "Float64": 141,
    "Valid": true
}

result in the JSON not just the value. Following the advice in the github issue above I tried to make a custom MarshalText() but it never gets called.

The code is at: https://gist.github.com/fils/3f557941d71f1a7165ca

The JSON produced is at: https://gist.github.com/fils/a01cadcbb5dc7c797c3e

The CSV dump function is obtaining and outputting the value only ok, but not sure how to get that effect for the JSON one too.

Using either sql.NullFloat64 or the custom type NullFloat64 give the same results.

答案1

得分: 1

你的NullFloat64不是一个encoding.TextMarshaler。请参考http://play.golang.org/p/AepGgQkOd7:

prog.go:25: 无法将NullFloat64字面量(类型为NullFloat64)分配给类型encoding.TextMarshaler:
	NullFloat64未实现encoding.TextMarshaler(MarshalText方法的类型错误)
		具有MarshalText() []byte
		期望MarshalText() ([]byte, error)

将你的方法改为:

func (nf NullFloat64) MarshalText() ([]byte, error) {
	if nf.Valid {
		nfv := nf.Float64
		return []byte(strconv.FormatFloat(nfv, 'f', -1, 64)), nil
	} else {
		return []byte("null"), nil
	}
}
英文:

Your NullFloat64 is not an encoding.TextMarshaler. See http://play.golang.org/p/AepGgQkOd7:

prog.go:25: cannot use NullFloat64 literal (type NullFloat64) as type encoding.TextMarshaler in assignment:
	NullFloat64 does not implement encoding.TextMarshaler (wrong type for MarshalText method)
		have MarshalText() []byte
		want MarshalText() ([]byte, error)

Change your method to

func (nf NullFloat64) MarshalText() ([]byte, error) {
	if nf.Valid {
		nfv := nf.Float64
		return []byte(strconv.FormatFloat(nfv, 'f', -1, 64)), nil
	} else {
		return []byte("null"), nil
	}
}

huangapple
  • 本文由 发表于 2015年9月28日 22:34:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/32825640.html
匿名

发表评论

匿名网友

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

确定