c# - 每当我尝试用枚举反序列化我的 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."}
解决方案
您不能直接反序列化为这样的枚举,您需要某种容器。例如:
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);
这将输出:
热
凉爽的
推荐阅读
- javascript - 页面重新加载不要求重新提交表单
- duplicates - 从多个 Coverity 运行中删除重复的结果
- c - 为什么我的静态变量在运行时会不对齐?
- git - 我有一个项目/文件夹的两个 .git 目录,如何重命名工作树中的文件?
- sqlite - SQLite C API 等效于 typeof(col)
- mxgraph - 如何将新属性添加到自定义边缘形状
- java - 如何使用 Selenium 和 Java 单击文本为 Ok 的元素
- node.js - 使用带有 multer 中间件的 axios post 发送文件时服务器响应“未定义”
- c# - 在 PowerPoint OpenXml C# 中访问特定的 TextBody
- swiftui - PickerView:如何水平居中并且没有空间?