ugorji / go

idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]
MIT License
1.86k stars 295 forks source link

*sql.Null structs satisfies encoding/json.Marshaler, but its MarshalJSON method is not called #92

Closed SchumacherFM closed 9 years ago

SchumacherFM commented 9 years ago

First, I thank you for the great project!

Given the following situation:

type NullString struct {
    sql.NullString
}
var nullString = []byte("null")

// MarshalJSON correctly serializes a NullString to JSON
func (n *NullString) MarshalJSON() ([]byte, error) {
    if n.Valid {
        j, e := json.Marshal(n.String)
        return j, e
    }
    return nullString, nil
}

NullString satisfies the encoding/json interface for custom marshaling. The json output of a NullString type would not be:

"Code":{"String":"de","Valid":true}

it will be

"Code":"de"

Is there a possibility to achieve the same with an additional interface on the type NullString with your encoder/decoder? 😀

SchumacherFM commented 9 years ago

Sorry ... should have better read the doc :-)

type Selfer interface {
    CodecEncodeSelf(*Encoder)
    CodecDecodeSelf(*Decoder)
}
ugorji commented 9 years ago

@SchumacherFM codec now supports (M|Unm)arshalJSON when using the JSON Handle. This may help make your transition easier.

SchumacherFM commented 9 years ago

Cool! Thanks! I've implemented your pkg here: https://github.com/corestoreio/csfw/blob/master/codegen%2FtableToStruct%2Fcodecgen%2Fgen.go

I'm afraid that I have to include your files because you didn't provide a public API.