Custom JSON marshal/unmarshal
January 28, 2023
Problem
Using Go we can have some freedom to use custom data type and customize the way of data will be encoded or decoded. Today we will learn about reading custom data with unique behavior.
I have json string like below, the requirement is reading price number as integer even though in json representative stored as string. How to solve this?
{"price":"6550","code":"ASII"}
Solution
In simple ways we have 2 solution:
- Using intermediate struct to marshal/unmarshal that act as data transfer object then transform to struct with price type int64.
// marshal/unmarshal json using DtoPricetype DtoTransaction struct { Price string `json:"price"` Code string `json:"code"` }// then convert to this structtype Transaction struct { Price int64 Code string}
- Custom JSON marshal/unmarshal
- Create custom type
StrInt64
with type aliasint64
- Implement
MarshalJSON
andUnmarshalJSON
to manage read string as int64 and vise versa.
Let's digging more in the code.
- Function
MarshalJSON
is quite simple we need to convert as string instead put value directly - Function
UnmarshalJSON
have 3 steps- Unmarshall as string
- Convert
string
toint64
- Type casting from
int64
toStrInt64
Prove it yourself if the implementation above is correct at https://go.dev/play/p/cnx_KdH3e2n (opens in a new tab)