简体   繁体   English

将Json字符串反序列化为Enum C#

[英]Deserialize Json string to Enum C#

I am writing a test on a custom version of stringEnumConverter. 我正在对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. 解析枚举时,我在反序列化行上遇到的异常是意外令牌StartObject。

I suspect it might be because I am representing the json string wrong, I also tried "{\\"none\\"}", "{\\"TestEnum\\":\\"none\\"}", "{TestEnum:none}", "{none}" and "none" . 我怀疑这可能是因为我表示的json字符串错误,我也尝试了"{\\"none\\"}", "{\\"TestEnum\\":\\"none\\"}", "{TestEnum:none}", "{none}" and "none"

{none} is not valid JSON, but 'none' is valid! {none}不是有效的JSON,但'none'是有效的!

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! 干杯!

If you serialize TestEnum.none into JSON, the result is "none" . 如果将TestEnum.none序列化为JSON,则结果为"none" A string is perfectly valid JSON. 字符串是完全有效的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. 您的JSON甚至不是有效的 JSON:*它是一个对象,*包含密钥(但密钥必须用双引号引起来),*不携带任何值。 (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. JSON.Net将为您做到这一点。 See 看到

.NET - JSON serialization of enum as string .NET-枚举的JSON序列化为字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM