Deserialize Json string to Enum C#

假如想象 提交于 2020-06-08 20:27:29

问题


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


回答1:


{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!




回答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\" }";


来源:https://stackoverflow.com/questions/56386362/deserialize-json-string-to-enum-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!