In Golang trying to deserialize to struct in golang

53 Views Asked by At

Actually Iam trying to fetch the data from the sql server (particular table), my expectation is to deserialize the data fetched from the sql server to struct in GoLang.

Declared the struct below

type TrnVmSeries struct {
    VmCode   sql.NullString
    IsHidden sql.NullBool
    Cores    sql.NullInt32
    Ram      sql.NullFloat64
}
func ReadSqlData() {
    var con *sql.DB = SqlConnection()
    defer CloseConnection(con)

    var resObj []model.TrnVmSeries

    rows, err := con.Query("select * from testGo")
    if err != nil {
        fmt.Println("Error executing query:", err.Error())
    }

    for rows.Next() {
        var vm model.TrnVmSeries
        if err := rows.Scan(&vm.VmCode, &vm.IsHidden, &vm.Cores, &vm.Ram); err != nil {
            fmt.Println(err)
        }
        resObj = append(resObj, vm)
    }

    jsonData, err := json.Marshal(resObj)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("Json serialized Data %v", string(jsonData))
    fmt.Println("Object Output", resObj[0])
}

I have tried this getting below output

`[ { "VmCode": { "String":"", "Valid":false }, "IsHidden":{ "Bool":false, "Valid":true }, "Cores":{ "Int32":0, "Valid":true }, "Ram": { "Float64":10, "Valid":true }

} ]`

But whats my expectation is below

[ { "VmCode": null, "IsHidden": false "Cores": 0 "Ram": 10 } ]

I don't know how to achieve this some one please help me on this. To get expected object. Also attached SQL table stucture

1

There are 1 best solutions below

3
dave On

You don't have to use sql.Null* - you can just use pointers:

type TrnVmSeries struct {
    VmCode   *string
    IsHidden *bool
    Cores    *int32
    Ram      *float64
}

Or you can have your own custom Null types that implement json marshaling the way you want, e.g.

type NullString sql.NullString
type NullBool sql.NullBool
type NullInt32 sql.NullInt32
type NullFloat64 sql.NullFloat64

func (s NullString) MarshalJSON() ([]byte, error) {
    if s.Valid {
        return json.Marshal(s.String)
    }
    return []byte(`null`), nil
}

// same thing for the other Null types...

type TrnVmSeries struct {
    VmCode   NullString
    IsHidden NullBool
    Cores    NullInt32
    Ram      NullFloat64
}

Per your comment, you also need to be able to print the object, in which case you just need to implement the Stringer interface, e.g. https://go.dev/play/p/AkV0_SvK6fi