[英]deserializing JSON file to Class that contains dictionary with dynamic key
我正在尝试将JSON文件反序列化为c#中的对象,该对象的结构与使用Newtonsoft的文件本身略有不同。
该文件的结构如下:
PointProperty:
{
"DataPointType": Foo
"PointTypeProperties: [
{
"PropertyName":
"PropertyValue":
"Requirement":
},
etc.
]
}
我正在尝试将JSON文件序列化为PointProperty和PointTypeProperty类:
public class PointProperty
{
public string DataPointType { get; set; }
public Dictionary<String,PointTypeProperty> PointTypeProperties { get; set; }
}
public class PointTypeProperty
{
public string PropertyValue { get; set; }
public string Requirement { get; set; }
}
在某种程度上,指向PointTypeProperties字典的键将是JSON文件中的PropertyName。 使用自定义解串器有什么办法可以做到这一点?
例如:
PointProperty:
{
"DataPointType": Alarm
"PointTypeProperties: [
{
"PropertyName": AlarmCheck
"PropertyValue": False
"Requirement": Mandatory
},
etc.
]
}
将反序列化为以下类:
``
public class PointTypeProperty
{
public string PropertyValue = False
public string Requirement = Mandatory
}
public class PointProperty
{
public string DataPointType = Alarm
public Dictionary<String,PointTypeProperty> PointTypeProperties = {"AlarmCheck": PointTypeProperty}
}
您不需要自定义序列化程序。 您可以使用DTO,可以轻松地将其转换为您的班级。
从逻辑PointTypeProperties
是JSON中的一个数组,因此请创建一个对该数组进行建模的DTO:
public class PointPropertyDto
{
public string DataPointType { get; set; }
public PointTypePropertyDto[] PointTypeProperties { get; set; }
}
public class PointTypePropertyDto
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
public string Requirement { get; set; }
}
将JSON反序列化为DTO图:
string json = @"
{
""DataPointType"": ""Foo"",
""PointTypeProperties"": [
{
""PropertyName"": ""Some name"",
""PropertyValue"": ""Some value"",
""Requirement"": ""Some requirement""
}
]
}";
var deserializedDto = JsonConvert.DeserializeObject<PointPropertyDto>(json);
然后,从DTO转换为原始类:
var deserialized = new PointProperty
{
DataPointType = deserializedDto.DataPointType,
PointTypeProperties = deserializedDto.PointTypeProperties.ToDictionary(p => p.PropertyName, p =>
new PointTypeProperty
{
PropertyValue = p.PropertyValue,
Requirement = p.Requirement
})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.