JsonUtility.FromJsonOverwrite not working with structs
This sample code doesn't modify SomeStruct b, nevertheless I hoped so:
SomeStruct a, b = new SomeStruct ();
// SomeStruct a changed: values copied at assignment
a = JsonUtility.FromJson<SomeStruct>(@"{""positionA"":{""x"":0.75,""y"":1.75,""z"":0.0}}");
// SomeStruct b not changed: being passed by value
// (Don't miss the 'b' variable at the end of next line)
JsonUtility.FromJsonOverwrite(@"{""positionA"":{""x"":0.75,""y"":1.75,""z"":0.0}}", b);
With SomeStruct defined as:
[System.Serializable]
struct SomeStruct
{
public Vector3 positionA;
}
Is this behaviour expected? In JsonUtility.FromJsonOverwrite documentation, there is no mention about this. Actually it is said that plain structs are supported.
Comment
Answer by superpig · Apr 21, 2017 at 12:06 PM
This is expected, due to boxing. Because FromJsonOverwrite's second parameter is of type 'object', passing a struct to it causes a boxed copy of the struct to be made. The copy is then overwritten, but when the function returns, the copy is discarded. For the original struct to be overwritten, you would have to pass it as 'ref b', which FromJsonOverwrite does not currently support.
We're updating the documentation to add a note about this.