[英]Create a custom resolver to map properties into separate models
I am writing a custom extension to DefaultContractResolver to map names between a JSON string and models to be deserialized.我正在为 DefaultContractResolver 编写一个自定义扩展到 JSON 字符串和要反序列化的模型之间的 map 名称。 The naming in these models is not consistent and I was specifically asked to not change them (renaming, adding attributes, etc).
这些模型中的命名不一致,特别要求我不要更改它们(重命名、添加属性等)。
The json looks like this json 看起来像这样
"parameter": {
"alarms": [
{
"id": 1,
"name": "alarm1",
"type": 5,
"min": 0,
"max": 2
}
],
"settings": [
{
"id": 1,
"name": "setting1",
"description": "something here"
"type": 1,
"value": 2
}
]
}
The Parameter class (output) has models for Alarms and Settings.参数 class(输出)具有警报和设置模型。 For example, these models look like this:
例如,这些模型如下所示:
public class Alarm
{
public int AlarmId { get; set; }
public string AlarmName { get; set; }
public AlarmType RbcType { get; set; }
public int MinimumTolerated { get; set; }
public int MaximumTolerated { get; set; }
}
public class Setting
{
public int SettId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public SettingType Type { get; set; }
public int IntValue { get; set; }
}
As an example the value of "id" in the json can relate to AlarmId or SettId, so I cannot have just one resolver to perform the ResolvePropertyName(string propertyName)例如,json 中“id”的值可能与 AlarmId 或 SettId 相关,因此我不能只有一个解析器来执行ResolvePropertyName(string propertyName)
And I don't know how to get about with this.我不知道该怎么做。
I don't think that you need any mapper, I would use this code我不认为你需要任何映射器,我会使用这段代码
var jObj = JObject.Parse(json)["parameter"];
var parameters = new
{
alarms = jObj["alarms"].Select(x => new Alarm { AlarmId = (int)x["id"], AlarmName = (string)x["name"] }).ToList(),
settings = jObj["settings"].Select(x => new Setting { SettId = (int)x["id"] }).ToList()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.