Is there a way to serialize an empty array attribute (not null) of a struct and deserialize it back to an empty array (not null again)?
Considering that an empty array is actually a pointer to null, is the perceptible initial difference between an empty array and pointer to null completely lost after serialize/deserialize?
The worst practical scenario is that when I show an empty array attribute to my REST client, as a json "att":[], at first time, and, after cache register to redis and recover it, the same attribute is shown to my client as "att":null, causing a contract broken and a lot of confusing.
Summing up: is possible to show the Customer 2 addresses like an json empty array, after serialize/deserialize => https://play.golang.org/p/TVwvTWDyHZ
I am pretty sure the easiest way you can do it is to change your line
var cust1_recovered Customer
to
cust1_recovered := Customer{Addresses: []Address{}}
Unless I am reading your question incorrectly, I believe this is your desired output:
ORIGINAL Customer 2 {
"Name": "Customer number 2",
"Addresses": []
}
RECOVERED Customer 2 {
"Name": "Customer number 2",
"Addresses": []
}
Here is a playground to verify with: https://play.golang.org/p/T9K1VSTAM0
The limitation here, as @mike pointed out, is if Addresses
is truly nil
before you encode, once you decode you do not get the json equivalent null
, but would instead end up with an empty list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With