![](/img/trans.png)
[英]Custom JSON contract resolver to ignore all properties without a custom annotation
[英]Create a custom resolver to map properties into separate models
我正在為 DefaultContractResolver 編寫一個自定義擴展到 JSON 字符串和要反序列化的模型之間的 map 名稱。 這些模型中的命名不一致,特別要求我不要更改它們(重命名、添加屬性等)。
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
}
]
}
參數 class(輸出)具有警報和設置模型。 例如,這些模型如下所示:
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; }
}
例如,json 中“id”的值可能與 AlarmId 或 SettId 相關,因此我不能只有一個解析器來執行ResolvePropertyName(string propertyName)
我不知道該怎么做。
我不認為你需要任何映射器,我會使用這段代碼
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.