JsonUtility vs null and/or empty strings

I have small problem with JSON conversions, here is a snippet:

StringTest[] sts = new StringTest[3];
sts[0] = new StringTest();
sts[0].test = "test";
sts[1] = new StringTest();
sts[1].test = "";
sts[2] = new StringTest();
sts[2].test = null;
UnityEngine.Debug.Log(UnityEngine.JsonUtility.ToJson(sts[0]));
UnityEngine.Debug.Log(UnityEngine.JsonUtility.ToJson(sts[1]));
UnityEngine.Debug.Log(UnityEngine.JsonUtility.ToJson(sts[2]));
[Serializable]
public class StringTest {
    public String test;
}

The result:
{“test”:“test”}
{“test”:“”}
{“test”:“”}

The expected result for me would be that the last block is either {} or {"test":null}, can this be achieved somehow? :slight_smile:

I think this case is related to this topic

under “No support for null for custom classes”

Also be mindful of the fact that if you hack the system and derive from UnityEngine.Object whose serialization does support null, that null doesn’t necessarily behave the same as C# null (it is in fact, an object in a “null” trenchcoat). I don’t know what else can arise from such scenarios, haven’t really gone down this route myself, but just so you’re aware of the side effects.

Oh, then, is there any JSON library that normally supports null objects? :slight_smile:

yes there are some, and I’m positive I had seen it mentioned here somewhere, but wouldn’t know to tell you more.
Unity’s JSON is relatively limited, or let’s say, a little bit basic in many regards. but I’m really not the best person telling you this, never used it myself, I’m just repeating what I’ve heard. maybe you can check out the asset store, not because you should immediately buy one, but because you can very easily detect how much of a glaring issue it happens to be.

Newtonsoft Json is the go to Json serializer for .Net, there was a package for Unity but never used it. You can always just add the library as is (.dll). Watch out for .net standard versions support though.
This assumes you are building for Windows with mono and not IL2CPP, don’t know if it works after the conversion.

1 Like

If you plan to use json.net, I suggest using this one GitHub - applejag/Newtonsoft.Json-for-Unity: Newtonsoft.Json (Json.NET) 10.0.3, 11.0.2, 12.0.3, & 13.0.1 for Unity IL2CPP builds, available via Unity Package Manager

1 Like

+1 for Brathnanns link.

Be aware that the Json.Net version offered for free in the AssetStore has not been updated since 2017. Judging by the reviews it still kinda works. I remember having to #ifdef some stuff for UWP when I was using it a few years ago.

I’ve just tried it (the built in one) and it works… thank you! :smile: