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
You don't have to use
sql.Null*- you can just use pointers:Or you can have your own custom Null types that implement json marshaling the way you want, e.g.
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