About JsonUtility and custom struct

Now I have these:

public struct lint
{
    private long value;

    private lint(int value)
    {
        this.value = value;
    }
    private lint(long value)
    {
        this.value = value;
    }

    public static implicit operator lint(int value)
    {
        return new lint(value);
    }

    public static implicit operator lint(long value)
    {
        return new lint(value);
    }
    public static implicit operator int(lint record)
    {
        return (int)record.value;
    }
    public static implicit operator long(lint record)
    {
        return record.value;
    }
    public override string ToString()
    {
        return value.ToString();
    }
}

And There is a test class:

    [System.Serializable]
    private class TestS
    {
        public lint zip;
    }

How can I make the lint work like a long or int?

TestS s = new TestS();
s.zip = 3;
Debug.Log(JsonUtility.ToJson(s));

This comes out {“zip”:{}},but I want {“zip”:3}

lint must also explicitly be set as Serializable:

[System.Serializable]
public struct lint
{
    ...

JsonUtility only handles things that would otherwise be drawn in the inspector. If Test was a MonoBehaviour, your zip variable would not be drawn.

1 Like

Well I forgot to copy that.Without [System.Serializable] it turns out {} ,not {“zip”:{}}

JsonUtility.ToJson
Generate a JSON representation of the public fields of an object.

Where are you public fields…

So I want the ‘lint’ work like ‘long’, and if i give

[SerializeField]
private long value;

It turns out:
{“zip”:{“value”:3}}
not
{“zip”:3}

That’s correct. Your zip contains a value field, and it’s set to 3. That’s how JSON works.

Unity’s JSONUtility doesn’t support overrides for serializing/deserializing types. If you need that, you’ll have to look for some other library.

What a pity…