繁体   English   中英

为 map 属性创建一个自定义解析器到单独的模型中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM