Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Array of Vector2 with Json.NET

I am trying to use Json.NET on Unity to serialize a class.
The class Polygon contains an Array of Vector2 but i only want to serialize the x and y variables of Vector2 class, that's why I'm using the JsonConverter attribute.

Sample class:

public class Polygon
{
    public int count { get; set; }

    [JsonConverter(typeof(Vector2Converter[]))]
    public Vector2[] points { get; set; }
}

It gives me this error at runtime:

MissingMethodException: Method not found: 'Default constructor not found...ctor() of JsonDotNet.Extras.CustomConverters.Vector2Converter[]

Anyone have any suggestions?

like image 207
John Avatar asked Feb 11 '26 03:02

John


1 Answers

The [JsonConverter] attribute takes the type of a converter, not the type of an array of converters. If your converter is designed to handle the serialization of the entire array, then you need to specify it like this:

    [JsonConverter(typeof(Vector2Converter))]
    public Vector2[] points { get; set; }

If your converter is designed to serialize the individual items in the array, you need to use this syntax instead:

    [JsonProperty(ItemConverterType=typeof(Vector2Converter))]
    public Vector2[] points { get; set; }
like image 153
Brian Rogers Avatar answered Feb 15 '26 18:02

Brian Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!