3

I have the following class:

public class Configuration
{
    public Color ErrorColor { get; set; }
    // other things
}

The Color struct is defined in a library I am using:

public struct Color
{
    public Color(uint rawValue) { /* ... */ }
    // other things
}

If I attempt to desterilize the following data:

{
    "ErrorColor": 16711680
}

With the following code:

var config = JsonConvert.DeserializeObject<Configuration>(data);

This exception gets thrown:

Newtonsoft.Json.JsonSerializationException: 'Error converting value 16711680 to type 'Discord.Color'.

How can I get Newtonsoft to call the constructor of this type when deserializing? I know you can make custom JsonConverter's, but I only need it for one property, not all of them.

Michael Smith
  • 1,271
  • 1
  • 8
  • 31
  • 2
    In short, the deserializer can only deal with parameterless constructors. You will need a custom converter like the answer here https://stackoverflow.com/questions/24726273/why-can-i-not-deserialize-this-custom-struct-using-json-net – ShuberFu Feb 03 '18 at 01:45
  • Take a look at [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/q/40480489). In your case you want to serialize your `ErrorColor` as a `uint` rather than a `string` but the idea is similar. Json.NET will generally only use a parameterized constructor when deserializing a JSON **object** or **array**. See https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm#JsonConstructorAttribute and [JSON.net: how to deserialize without using the default constructor?](https://stackoverflow.com/q/23017716/3744182). – dbc Feb 03 '18 at 02:00

0 Answers0