Override JSON Marshalling in GO

Dimas Ragil Triatmaja
2 min readMay 14, 2019

--

Override JSON marshal and unmarshal interface I using for manipulated JSON request and response from the client. The example is to parse milliseconds to the string of date.

We are will override the Unmarshal JSON interface to parse the milliseconds to the string of date

The code in above, we are created new Go struct and override function UnmarshalJSON to handle JSON value and parse milliseconds to a time string with format RFC3339 in Go and then assign the value to the Profile struct, if success we can use Profile struct with the value we got from JSON.

Sometimes I also override Marshal function to manipulated JSON response to hide some fields to the client.

Besides this, we are also could use interface to handle the request like this bellow.
This request has a type and with different fields inside the format field

Firstly we create a struct to handle JSON request and create one more struct with an interface within and we override JSON Marshaling and Unmarshall same as before to handle the request body but in here we use conditional to check type field and put the format field to appropriate struct.

We see the JSON request put to the interface with the specific field. the key is the type field, this field use to check the type and put the value to an appropriate struct. but the format interface still cannot be called, we should implement the interface like this bellow.

With this implementation, the interface could call to the function and could assign the value. we could casting interface to revert back to the JSON response with appropriate format same as before.

Now we could try to make a request and see the result.

result interface

From the result, we could parse the payload to the appropriate struct and revert it back to appropriate JSON payload just the same as before.

--

--