首页 > 解决方案 > 每当我尝试用枚举反序列化我的 json 时,我都会不断收到错误

问题描述

这是我的枚举代码

[JsonConverter(typeof(StringEnumConverter))]
        public enum SystemSwitch
        {
            EmergencyHeat = 0,
            Heat = 1,
            Off = 2,
            Cool = 3,
            Autoheat = 4,
            Autocool = 5,
            SouthernAway = 6,
            Unknown = 7
        }

我要反序列化这个json

var a = @"{'SystemSwitch': 'Heat','HeatCoolMode': 'Cool'}";
            try
            {
                var parsedEventData = Newtonsoft.Json.JsonConvert.DeserializeObject<SystemSwitch>(a);
                Console.WriteLine(parsedEventData);
            }

但我收到一个例外说

{"Unexpected token StartObject when parsing enum. Path '', line 1, position 1."}

如果我尝试使用 json 字符串

string a = "'SystemSwitch':'Cool'";

我明白了

{"Error converting value \"SystemSwitch\" to type 'Testing.Program+SystemSwitch'. Path '', line 1, position 14."}

标签: c#jsondeserializationenumerationjson-deserialization

解决方案


您不能直接反序列化为这样的枚举,您需要某种容器。例如:

public class Container
{
    public SystemSwitch SystemSwitch { get; set; }
    public SystemSwitch HeatCoolMode { get; set; }
}

现在你可以这样做:

var a = @"{'SystemSwitch': 'Heat','HeatCoolMode': 'Cool'}";
var parsedEventData = Newtonsoft.Json.JsonConvert.DeserializeObject<Container>(a);
Console.WriteLine(parsedEventData.SystemSwitch);
Console.WriteLine(parsedEventData.HeatCoolMode);

这将输出:

凉爽的


推荐阅读