Stop specific fields from being serialized by JSON utility

Hi

I am saving some info about objects in a .json file and that object has some “editor only” fields to only set where the object should send some messages but these fields are also being serialized and added to the .json file. It isn’t a “problem”, really, but the fields are taking up some unnecessary space. I tried adding the “[System.NonSerializable]” attribute to the fields but that just disables them from being viewed at all and caused problems with the custom editor script I am using for this.

So any help with this would be greatly appreciated!

(I’m also not showing any code because I don’t see any point in showing the code I have. It is basically a class with a few variables and then JsonUtility.ToJson())

Unity’s JsonUtility does work exactly the same as the usual serialization inside the editor. So by default it will only serialize public variables. With the SerializeField attribute you can make it serialize private variables and with NonSerialized you can prevent a variable from being serialized.

However if you want a certain variable be serialized in the editor but not by the JsonUtiltiy, that’s not possible as they work exactly the same. The JsonUtility is ment to provide a serialization method at runtime. If you just want to serialize a subset of a class, you would have to create a seperate data class with the fields you want to serialize. There’s no other way. The only alternative would be to manually parse the created JSON text and remove the unwanted information from there.

Yes I found the [JsonIgnore] attribute before, but it doesn’t appeart to exist in Unity. Perhaps it’s because Unity has it’s own Json Utility that seems to be different than the standard .NET

use the [System.NonSerialized] attribute.

[System.NonSerialized] public GameObject myGameObject;

Hi,
You can use the [JsonIgnore] attribute to prevent it from being written to a Json file and still keep it serialized to be open in the inspector like this:

usingSystem.IO;

[JsonIgnore][SerializeField] string yourFieldHere;