#JsonUtility always loads nullable types as null

1 messages · Page 1 of 1 (latest)

small prairie
#

json file:

{
    "things": [
        {
            "name": "car",
            "speed": 40
        },
        {
            "name": "knife",
            "sharpness": 8
        }
    ]
}

c# file:

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class TestJson : MonoBehaviour
{
    public TextAsset testJson;

    void Start()
    {
        List<Thing> things = JsonUtility.FromJson<Things>(testJson.text).things.ToList();

        foreach (Thing thing in things)
        {
            Debug.Log(thing.name + ", " + thing.speed + ", " + thing.sharpness);
        }
    }
}

[System.Serializable]
public class Thing
{
    public string name;
    public float? speed;
    public float? sharpness;
}

[System.Serializable]
public class Things
{
    public Thing[] things;
}

As you can see I have made the floats, speed and sharpness, nullable, as I want their values to be null if a thing doesn't have that field. However, the output in the log is:

#

As you can see, every field has been set to null, even though the car does have a speed, and the knife does have a sharpness.

Removing the question marks after float (i.e. making them non-nullable) yields the following:

#

So it is capable of reading these fields, but for some reason it just decides nullable ones are always null? What am I doing wrong?

potent chasm
#

could you try doing it without ToList()
not sure but i found something that says that might be the issue

#

also you could try using newtonsoft json or System.Text.Json
might as well just be an issue with unity's json library lol

small prairie
#

Nah it still doesnt work. I think it must be an issue with unity's json library. Looking at the docs it has like no customisability or options at all so guess thats that

#

Guess I'll try another json libraray, thanks

potent chasm
#

yea newtonsoft and System.Text.Json are the popular ones in C#

small prairie
#

newtonsoft works, thanks :) and it is included in unity or c# by default too it seems, which is nice

terse chasm