C# 使用JSON反序列化的枚举始终为0
我有一个参数类,它的属性TypeOfParameter是一个枚举:C# 使用JSON反序列化的枚举始终为0,c#,json,enums,C#,Json,Enums,我有一个参数类,它的属性TypeOfParameter是一个枚举: public ParameterType TypeOfParameter { get; set; } public enum ParameterType {Completion, Boolean, Numeric, Range, Text, Undefined }; 当我序列化它(使用Biggy JSON数据存储)时,它正确地将数字参数序列化为2: "TypeOfParameter":2 但是当我检索/反序列化参数时,它总
public ParameterType TypeOfParameter { get; set; }
public enum ParameterType {Completion, Boolean, Numeric, Range, Text, Undefined };
当我序列化它(使用Biggy JSON数据存储)时,它正确地将数字参数序列化为2:
"TypeOfParameter":2
但是当我检索/反序列化参数时,它总是为ParameterType返回0(Completion)。参数有两个构造函数。一个允许我传入所有属性的值,另一个是无参数构造函数。当数据被反序列化并且所有其他属性都被正确分配时,将调用无参数构造函数。只有枚举分配不正确
知道我做错了什么吗
编辑:
下面是参数类和JSON。注意,JSON用于我的示例类,它有一个列表,SampleTest有一个列表
public class Parameter
{
public string ParameterName { get; set; }
public string Unit { get; set; }
public ParameterType TypeOfParameter { get; set; }
public double? LowerLimit { get; set; }
public double? UpperLimit { get; set; }
public bool Selected { get; set; }
public string Formula { get; set; }
public Parameter(string name, string unit, ParameterType typeOfParameter = ParameterType.Numeric,
double? lowerLimit = null, double? upperLimit = null)
{
this.ParameterName = name;
this.Unit = unit;
this.TypeOfParameter = typeOfParameter;
this.LowerLimit = lowerLimit;
this.UpperLimit = upperLimit;
this.Selected = true;
}
public Parameter()
{ }
public void ToggleSelection()
{
this.Selected = !this.Selected;
}
public enum ParameterType {Completion, Boolean, Numeric, Range, Text, Undefined };
}
JSON:
你能展示一下你的JSON和类的例子吗?还要看一看这个线程-确保您没有在某个地方打开。@dbc:我没有打开StringEnumConverter,但我确实尝试打开它,看看这是否会改变结果。事实并非如此。谢谢你的建议。@Chris:我添加了你要求的信息。我看了你推荐的线。我认为,也许,因为一个示例有一个SampleTests列表,一个SampleTest有一个参数列表,所以这个线程可能会应用。但是,所有其他参数属性都使用我当前的代码进行了正确的反序列化,因此我不知道枚举的行为为何会有所不同。@blueshift您以前是否尝试过使用enum-
[JsonConverter(typeof(StringEnumConverter))]
执行此方法`公共枚举TestType{[EnumMember(Value=“TestValue1”)]Test1='TestValue1',[EnumMember(Value=“TestValue2”)]Test2='TestValue2'}
[
{
"SampleID": "150000001",
"SampleName": "Json1",
"Status": 0,
"EditType": 0,
"Tests": [
{
"Results": [
{
"Value": "444",
"RunNumber": 1,
"InSpec": true,
"ParameterName": "NA",
"Unit": "ppm",
"TypeOfParameter": 2,
"LowerLimit": null,
"UpperLimit": null,
"Selected": true,
"Formula": null
},
{
"Value": "555",
"RunNumber": 1,
"InSpec": true,
"ParameterName": "K",
"Unit": "ppm",
"TypeOfParameter": 2,
"LowerLimit": null,
"UpperLimit": null,
"Selected": true,
"Formula": null
}
],
"Status": 1,
"Lab": "AA",
"TestName": "W:NA,K",
"Parameters": [
{
"ParameterName": "NA",
"Unit": "ppm",
"TypeOfParameter": 2,
"LowerLimit": null,
"UpperLimit": null,
"Selected": true,
"Formula": null
},
{
"ParameterName": "K",
"Unit": "ppm",
"TypeOfParameter": 2,
"LowerLimit": null,
"UpperLimit": null,
"Selected": true,
"Formula": null
}
],
"TypeOfTest": 0
}
]
}
]