Trouble getting JSON DeserializeObject to work on this class

I am trying to deserialize the following class using Json.Net and receiving the error:

Error converting value "abc" to type 'System.UInt16'. Path 'typestr'

public class TestClass 
{
    [JsonIgnore]
    public static ushort TEST_TYPE_A = 0;

    [JsonIgnore]
    public static ushort TEST_TYPE_B = 1;

    [JsonProperty("typestr")]
    public string typestr {get; set;}

    [JsonProperty("testvalue")]
    public string testvalue {get; set;}

    [JsonProperty("bob")]
    public string bob {get; set;}

    public TestClass(ushort typestr)
    {
        this.typestr = types[typestr];
    }

    public void Init() { }
}


TestClass a = JsonConvert.DeserializeObject<TestClass>("{\"typestr\": \"abc\"}");

Does anyone know how to get around this error?

Jon Skeet
people
quotationmark

You've provided JSON with a property of typestr which has a string value. You've also got two parts called typestr in your class:

  • A property (type string)
  • A constructor parameter (type ushort)

Json.NET could use either of those, but apparently the constructor parameter takes precedence - which makes some sense given that you haven't provided any other constructors.

You can:

  • Change the name of the constructor parameter
  • Provide a parameterless constructor

Either of those seems to do the trick - I would personally provide a parameterless constructor if you don't expect the JSON values to be used in the constructor call.

people

See more on this question at Stackoverflow