将Json字符串反序列化为Enum C# [英] Deserialize Json string to Enum C#
问题描述
我正在对stringEnumConverter的自定义版本编写测试。但是当我反序列化时,我的测试不断抛出。我搜索了堆栈溢出,但是找不到我做错了什么。以下是我在做什么的示例:
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);
}
}
}
我遇到的例外解析枚举时,反序列化行是意外令牌StartObject。
The exception I get on the deserialize line is Unexpected token StartObject when parsing enum.
我怀疑这可能是因为我表示的json字符串错误,我也尝试过 {\ none\}, {\ TestEnum\:\ none\}, {TestEnum:none}, {none}和 none
。
I suspect it might be because I am representing the json string wrong, I also tried "{\"none\"}", "{\"TestEnum\":\"none\"}", "{TestEnum:none}", "{none}" and "none"
.
推荐答案
{none}不是有效的JSON,但'none'是有效的!
{none} is not valid JSON, but 'none' is valid!
您应该尝试以下操作:
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var jsonString = "'none'";
var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
Console.WriteLine(deserializedObject);
}
}
干杯!
这篇关于将Json字符串反序列化为Enum C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!