Why are my null JSON variables returning fully initialized?

I’m using a JsonUtility.ToJson and FromJson to save/load data. One part of the data for example is an InventorySlot class who has a public variable Item that by default is null. When creating a new character I specify their equipment as a list of 12 new InventorySlot() which means that there should be 12 null Item variables within the list.

However, when I FromJson the saved data back all of the Item variables within each InventorySlot are initialized as a new Item(), not as a null.

This breaks past all my null reference checks within the game… I could rewrite the checks, not a HUGE deal, but is there an easy way to make Json save null as null? Some option I am missing?

Sample code: The InventorySlot class:

[Serializable]
public class InventorySlot {

	public int slotNumber = -1;
	public int itemAmount = 0;
	public Item item = null;
	public InventorySlotTypes slotType = InventorySlotTypes.Null;

}

the InventorySlot being initialized during character creation (new save file creation):

        //initialize equipment
		for (int i = 0; i <= 18; i++) {
			this.equipmentSlots.Add(new InventorySlot());
			this.equipmentSlots*.slotNumber = i;*

_ this.equipmentSlots*.slotType = InventorySlotTypes.Equipment;_
_
}*_
There is no touching of the equipmentSlots after that, I then toJson, binaryformatter serialize to a file, deserialize on load, and fromJson back, and all of the item variables are initialized as new Item()…?

It seems that JSON will force serialization on anything and everything it touches. Simply writing out binary data did not force serialization on null objects so I never ran into this before.

I’ve found that even calling ToJson with the equipment list being reference will force serialization on the entire list and all child variables even in runtime. Even copying the list without explicit recreation of any nested non-generics (ie: child lists) would serialize all said variables removing any and all null values in runtime (big probs if you are expecting things to be null).

Using a check on load to look for any Item with the default values and setting it to null before importing solved that. And making sure to use " new List(ListToSave) " on anything being pulled into the class ToJson will be called on (including all nested classes) prevented runtime serialization of anything I didn’t want changed.

Unity’s JsonUtility class behaves roughly the same as it’s normal serialization system but will less features. So have a look at the script serialization documentation. Especially the section “When might the serializer behave unexpectedly?”