-1

I am writing a custom extension to DefaultContractResolver to map names between a JSON string and models to be deserialized. 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

"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. 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)

And I don't know how to get about with this.

Jaime Oliveira
  • 751
  • 1
  • 5
  • 13
  • 1
    You can use a [custom contract resolver](https://www.newtonsoft.com/json/help/html/contractresolver.htm#CustomIContractResolverExamples) to rename properties in runtime. See the answer by Brian Rogers to [Json.NET deserialize or serialize json string and map properties to different property names defined at runtime](https://stackoverflow.com/a/38112291). Does that answer your question? – dbc Dec 28 '22 at 18:18

1 Answers1

0

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()
    };
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Although Im not insisting in using a custom mapper or resolver, I dont think this would be ideal because the JSON / models are bigger and with more complex types than what I posted in the question. I shared a simple representation of I wanted to do. – Jaime Oliveira Dec 28 '22 at 09:47
  • @JaimeOliveira You have to think twice. I don't see any difference between this code and mapper except this is much more flexible and clear. The bigger the real json , the bigger the mapper too. – Serge Dec 28 '22 at 13:34