普通网友 2018-08-22 07:00 采纳率: 0%
浏览 181
已采纳

您如何编组sql.NullString以便将输出展平以仅给出go中的值?

Given a go struct

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

when marshalled with something like this

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

the result is

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

The result desired is

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

I've tried explicitly stating that Abn is a string.

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

which did not change the result.

How do you marshal a sql.NullString such that the output is flattened to give just the value in go?

EDIT

Something like I ended up with after reading the answers from https://stackoverflow.com/users/8256506/nilsocket and 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"`         
}
  • 写回答

2条回答 默认 最新

  • dongnan4571 2018-08-22 07:35
    关注

    Here is the code,

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

    Here is the blog post which explains it in detail.

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

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况