Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang serialize/deserialize an Empty Array not as null

Tags:

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

like image 331
DLopes Avatar asked Oct 17 '15 05:10

DLopes


1 Answers

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.

like image 104
sberry Avatar answered Sep 26 '22 18:09

sberry