每当我尝试用枚举反序列化json时,我都会不断出错

问题描述 投票:1回答:1

这是我的枚举代码

[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# json deserialization enumeration json-deserialization
1个回答
1
投票

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

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);

将输出:

© www.soinside.com 2019 - 2024. All rights reserved.