SQL NullString problem [SOLVED]

Hey there, why if I use type sql.NullString and when serialize it to json I have the following result?

"SerieSatelital":{"String":"","Valid":false}

Instead of:

"SerieSatelital":null

I’m doing it that way;

err := rows.Scan(&v.IdVeiculoGrupo, &v.Identificacao, &v.SerieSatelital)
.....................
...............
.........

json.NewEncoder(w).Encode(&Veiculos)

What should I do to get the correct null format when serialized to json?

Hey there, why if I use type sql.NullString and when serialize it to json I have the following result?

sql.NullString is a struct. The output you see is the default way structs are encoded/marshaled to JSON (using reflection).

What should I do to get the correct null format when serialized to json?

Two ways come to mind:

  1. Use *string instead of sql.NullString
  2. Embed sql.NullString in a type that implements json.Marshaler, then use that type instead

https://play.golang.org/p/p99pXnr0dx shows how both these methods work.

I tend to use pointers to represent nullable values.

2 Likes

Thanks my friend!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.