How to make go decoding/unmarshalling api set zero value instead of returning error?

Suppose, i have a struct with field of int. If i send a json string from client side to server and if this filed contains some characters instread of digits, go causes an error while decoding/unmarshalling json string. so how to make go set zero value instead of causing an error.

Struct Example:

type Form struct {
    Age int
}

Json string:

{"Age": "23abc"}

Can you give an example how such invalid JSON looks like?

Two options that come to mind are json.Number (which is essentially a string) and a custom unmarshaller:

https://play.golang.org/p/eFSiBZDFrNS

2 Likes

Cool. Thank you.

2 Likes

BTW, this post has the nice ID 7777. Let’s go for 8888 :slight_smile:

2 Likes

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