How to catch/handle missing value fields while deserializing JSON

Hi,
I’m trying for catch and handle missing json fields while deserializing text data files. Fields are Int32 indices where ‘0’ just cannot stand for ‘no data’ but is allowed to be missing in a file and it must be catched and replaced with specific default value. Problem is - I can’t tell which values are missing because some values are defined as ‘0’ deliberately.

DefaultValue attribute looks like a good candidate for that but JsonUtility seems to totally ignore it (?). I also tried this with “com.unity.nuget.newtonsoft-json”: “2.0.0” but it didn’t work either (a bug or my fault, cant tell).

I ended up going with SimpleJSON i.e. manual path for now but I’m sure sb figured this out already, haven’t you?

You’re probably fine using SimpleJson if it’s working.

I’m using this 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 for my json.net.

Another thing that I’ve done with json.net is this

string jsonString = JsonConvert.SerializeObject(someClassData, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });

The JsonSerializerSettings will keep null values from being included in the json string. The one other key thing though is that ints by their nature aren’t nullable by default, so you want it to be a nullable type.

public class TestData
{
    public int? testInt { get; set; }
    public string testString { get; set; }
}
public class TestDataManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        TestData td1 = new TestData();
        td1.testInt = 1;
        string td1String = JsonConvert.SerializeObject(td1, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });

        Debug.Log(td1String);

        TestData td2 = new TestData();
        td2.testString = "string";
        td2.testInt = null;
        string td2String = JsonConvert.SerializeObject(td2);//, new JsonSerializerSettings
        //{
        //    NullValueHandling = NullValueHandling.Ignore
        //});

        Debug.Log(td2String);
    }
}

The values printed out
{“testInt”:1}
{“testInt”:null,“testString”:“string”}

Of course, if you uncomment out the JsonSerializerSettings on the second one, it will just be
{“testString”:“string”}

Hope this helps.

1 Like