6

I am writing a test on a custom version of stringEnumConverter. But my test keeps throwing when I deserialize. I searched over stack overflow, but could not find what I did wrong. Following is a sample of what I'm doing:

namespace ConsoleApp2
{
    [Flags]
    [JsonConverter(typeof(StringEnumConverter))]
    enum TestEnum
    {
        none = 0, 
        obj1 = 1,
        obj2 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{none}";
            var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        }
    }
}

The exception I get on the deserialize line is Unexpected token StartObject when parsing enum.

I suspect it might be because I am representing the json string wrong, I also tried "{\"none\"}", "{\"TestEnum\":\"none\"}", "{TestEnum:none}", "{none}" and "none".

Yituo
  • 1,458
  • 4
  • 17
  • 26

2 Answers2

6

{none} is not valid JSON, but 'none' is valid!

You should try the following:

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var jsonString = "'none'";
        var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        Console.WriteLine(deserializedObject);
    }
}

Cheers!

Cristián Ormazábal
  • 1,457
  • 1
  • 9
  • 18
2

If you serialize TestEnum.none into JSON, the result is "none". A string is perfectly valid JSON.

Your JSON isn't even valid JSON: * It is an object, * containing key (but keys must be quoted with double quoted), * that carries no value. (and an object key must have a value)

So... try something like this:

var jsonString = "\"none\"";
var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);

But you shouldn't have to write a custom serializer. JSON.Net will do it for you. See

.NET - JSON serialization of enum as string

But if you want to deserialize an object containing your enum, you'll want something along these lines:

{
  "enumKey" : "none"
}

Which would be something like this in your test:

var jsonString = "{ \"enumKey\" : \"none\" }";
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135