bytedance / sonic

A blazingly fast JSON serializing & deserializing library
Apache License 2.0
6.59k stars 327 forks source link

Any solution for parse sql.NullString field failed? #584

Closed rts-gordon closed 5 months ago

rts-gordon commented 5 months ago

Hi there,

There is a struct include a sql.NullString field, it will be failed when parse json data with this struct, is there any solution for this issue? Thank you.

type Account struct {
    Tenant   string `json:"tenant,omitempty"`
    Platform string `json:"platform,omitempty"`
    ServerId string `json:"server_id,omitempty"` 
    Login    int64  `json:"login,omitempty"`
    Name     string `json:"name,omitempty"`
    Group    string `json:"group,omitempty"`
    Tag       sql.NullString `json:"tag,omitempty"`
}

error message:

{"level":"error","ts":1706828964.7658167,"msg":"Unmarshal account tag failed, error: Mismatch type sql.NullString with value string \"at index 819: mismatched type with value\\n\\n\\t:\\\"server_id1\\\",\\\"tag\\\":\\\"tag1\\\"\\n\\t................^...............\\n\", message: {\"tenant\":\"tenant1\",\"platform\":\"platform1\",\"login\":123456,\"server_id\":\"server_id1\",\"tag\":\"tag1\"}
AsterDY commented 5 months ago

sql.NullString is a struct instead of a string. If you want use it as string, Please implement json.Unmarshaler on it

rts-gordon commented 5 months ago

Hi @AsterDY I implement json.Unmarshaler interface, it is works for encoding/json, but not works for sonic/Unmarshal. Which interface I should implment in sonic? thank you very much.

// NullString is an alias for sql.NullString data type
type NullString sql.NullString

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

// UnmarshalJSON for NullString
func (ns *NullString) UnmarshalJSON(b []byte) error {
    err := json.Unmarshal(b, &ns.String)
    ns.Valid = (err == nil)
    return err
}