- Published on
Custom JSON marshal/unmarshal
- Authors
- Name
- Moch Lutfi
- @kaptenupi
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?
_1{"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.
_11// marshal/unmarshal json using DtoPrice_11type DtoTransaction struct {_11 Price string `json:"price"`_11 Code string `json:"code"` _11}_11_11// then convert to this struct_11type Transaction struct {_11 Price int64 _11 Code string_11}
- 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