How to handle sql.NullString, sql.NullInt64,

Hi!

I’m stuck trying to override the default behaviour of c.JSON(…).

I have some NULL values in my records, so I defined structures like this:

type User struct {
	ID        int            `json:"ID" sql:"id"`
	Username  string         `json:"Username" sql:"username"`
	Password  string         `json:"Password" sql:"password"`
	Email     sql.NullString `json:"Email" sql:"email"`
	SocketID  sql.NullInt64  `json:"SocketID" sql:"SocketID"`
	Enabled   sql.NullInt64  `json:"Enabled" sql:"Enabled"`
	SessionID sql.NullString `json:"SessionID" sql:"SessionID"`
	Avatar    sql.NullString `json:"Avatar" sql:"Avatar"`
	State     sql.NullString `json:"State" sql:"State"`
	Hidden    sql.NullString `json:"Hidden" sql:"Hidden"`
}

Handling the request to GET users, I use this json response:

return c.JSON(http.StatusOK, response)

For sql.Null… values, I get:

  "Email": {
    "String": "",
    "Valid": false
  },
  "SocketID": {
    "Int64": 0,
    "Valid": false
  },

I’m trying to override the default Marshal using:

type NullString sql.NullString

func (x *NullString) MarshalJSON() ([]byte, error) {
if !x.Valid {
return []byte("null"), nil
}
return json.Marshal(x.String)
}

But I can’t get a json with just the value (or blank string).

How did you manage this?

Thank you. :slight_smile: