json - 您如何编码 sql.NullString 以便输出被展平以仅给出 go 中的值?

标签 json go marshalling

给定一个结构体

type Company struct {
    ID   int             `json:"id"`              
    Abn  sql.NullString  `json:"abn,string"`
}

当用这样的东西编码时

company := &Company{}
company.ID = 68
company.Abn = "SomeABN"
result, err := json.Marshal(company)

结果是

{
    "id": "68",
    "abn": {
        "String": "SomeABN",
        "Valid": true
    }
}

想要的结果是

{
    "id": "68",
    "abn": "SomeABN"
}

我已经尝试明确说明 Abn 是一个字符串。

Abn  sql.NullString  `json:"abn,string"`

这并没有改变结果。

如何编码 sql.NullString 以便将输出展平以仅提供 go 中的值?

编辑

我在阅读了 https://stackoverflow.com/users/8256506/nilsocket 的答案后得出的结论和 https://stackoverflow.com/users/965900/mkopriva

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"`         
}

最佳答案

你不能,至少不能只使用 sql.NullStringencoding/json

您可以做的是声明一个嵌入 sql.NullString 的自定义类型,并让该自定义类型实现 json.Marshaler 接口(interface)。

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"`
}

https://play.golang.org/p/Ak_D6QgIzLb

关于json - 您如何编码 sql.NullString 以便输出被展平以仅给出 go 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51961358/

相关文章:

java - 使用 Java 中的属性文件中的嵌套字段创建 map 或对象

json - 如何使用 Go 从 JSON 文件中读取一个值

C# 性能 - 使用不安全指针代替 IntPtr 和 Marshal

ios - 即使在展开它之后也可以选择具有值(value)

node.js - 为什么我的 AWS Lambda 函数返回 "Invalid JSON"错误?

node.js - 在 golang 中为 http 响应创建自定义错误

go - Gopath已在个人资料中设置,但仍看不到Go版本

java - 合适的 XML 编码器和解码器

json - 戈朗 : Multiple structs marshall issue: json format

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined