9

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".

asked May 30, 2019 at 22:23
2
  • 2
    {none} is not a valid json to begin with. Commented May 30, 2019 at 22:30
  • A valid json would be something like: {test: none} Commented May 30, 2019 at 22:31

2 Answers 2

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!

answered May 30, 2019 at 22:33
0
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\" }";
answered May 31, 2019 at 1:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.