Kei*_*son 12 json marshalling go
给定一个 go 结构
type Company struct {
ID int `json:"id"`
Abn sql.NullString `json:"abn,string"`
}
Run Code Online (Sandbox Code Playgroud)
当用这样的东西编组时
company := &Company{}
company.ID = 68
company.Abn = "SomeABN"
result, err := json.Marshal(company)
Run Code Online (Sandbox Code Playgroud)
结果是
{
"id": "68",
"abn": {
"String": "SomeABN",
"Valid": true
}
}
Run Code Online (Sandbox Code Playgroud)
想要的结果是
{
"id": "68",
"abn": "SomeABN"
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试明确说明 Abn 是一个字符串。
Abn sql.NullString `json:"abn,string"`
Run Code Online (Sandbox Code Playgroud)
这并没有改变结果。
您如何编组 sql.NullString 以便将输出展平以仅给出 go 中的值?
编辑
在阅读了/sf/users/577955451/和/sf/users/67613031/的答案后,我得到了类似的结果
package main
import (
"database/sql"
"encoding/json"
"reflect"
//"github.com/lib/pq"
)
/*
https://medium.com/aubergine-solutions/how-i-handled-null-possible-values-from-database-rows-in-golang-521fb0ee267
*/
type NullString sql.NullString
func (x *NullString) MarshalJSON() ([]byte, error) {
if !x.Valid {
x.Valid = true
x.String = ""
//return []byte("null"), nil
}
return json.Marshal(x.String)
}
// Scan implements the Scanner interface for NullString
func (ns *NullString) Scan(value interface{}) error {
var s sql.NullString
if err := s.Scan(value); err != nil {
return err
}
// if nil then make Valid false
if reflect.TypeOf(value) == nil {
*ns = NullString{s.String, false}
} else {
*ns = NullString{s.String, true}
}
return nil
}
type Company struct {
ID int `json:"id"`
Abn NullString `json:"abn"`
}
Run Code Online (Sandbox Code Playgroud)
mko*_*iva 11
你不能,至少不能只使用sql.NullString
and encoding/json
。
您可以做的是声明一个嵌入的自定义类型sql.NullString
并让该自定义类型实现该json.Marshaler
接口。
type MyNullString struct {
sql.NullString
}
func (s MyNullString) MarshalJSON() ([]byte, error) {
if s.Valid {
return json.Marshal(s.String)
}
return []byte(`null`), nil
}
type Company struct {
ID int `json:"id"`
Abn MyNullString `json:"abn,string"`
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/Ak_D6QgIzLb
这是代码,
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
)
//Company details
type Company struct {
ID int `json:"id"`
Abn NullString `json:"abn"`
}
//NullString is a wrapper around sql.NullString
type NullString sql.NullString
//MarshalJSON method is called by json.Marshal,
//whenever it is of type NullString
func (x *NullString) MarshalJSON() ([]byte, error) {
if !x.Valid {
return []byte("null"), nil
}
return json.Marshal(x.String)
}
func main() {
company := &Company{}
company.ID = 68
//create new NullString value
nStr := sql.NullString{String: "hello", Valid: true}
//cast it
company.Abn = NullString(nStr)
result, err := json.Marshal(company)
if err != nil {
log.Println(err)
}
fmt.Println(string(result))
}
Run Code Online (Sandbox Code Playgroud)
这是详细解释它的博客文章。
归档时间: |
|
查看次数: |
6337 次 |
最近记录: |