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 
    public static ushort TEST_TYPE_A = 0;

    public static ushort TEST_TYPE_B = 1;

    public string typestr {get; set;}

    public string testvalue {get; set;}

    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

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.


See more on this question at Stackoverflow