1

I need help, how can I shorten this code. I have a response message which I need to deserialize based on code type. the deserialization is of different classes. Below code works if I write for each loop inside each "if"statement but I am looking for a better way to write this

private async Task GetMappedCode( string id, List<string> mappedCode, string dresponseMessage, string codeType)
        {            
            if (codeType == "discipline")
            {
               var myDeserializedClass = new List<DisciplineCode>();
               myDeserializedClass = JsonConvert.DeserializeObject<List<DisciplineCode>>(dresponseMessage);
            }
            else if(codeType == "system")
            {
                var myDeserializedClass = new List<SystemCode>();
                myDeserializedClass = JsonConvert.DeserializeObject<List<SystemCode>>(dresponseMessage);
            }
            
            foreach (var did in myDeserializedClass)
            {
                if (did.id == $"rdl:{id}")
wajaap
  • 273
  • 3
  • 20
ZZZSharePoint
  • 1,163
  • 1
  • 19
  • 54

1 Answers1

1

You have to refactor your code to another function and use string to type dictionary

Dictionary<string, Type> CodeTypes = new Dictionary<string, Type>()
{
    { "discipline", typeof(DisciplineCode)},
    { "system", typeof(SystemCode)}
};

private async Task GetMappedCode( string id, List<string> mappedCode, string dresponseMessage, string codeType)
{
    var myDeserializedClass = typeof(YourClass)
       .GetMethod("GetDeserializedList")
       .MakeGenericMethod(CodeTypes[codeType])
       .Invoke(this, dresponseMessage);

    etc ...
}

private IList<T> GetDeserializedList<T>(string serializedJson) => JsonConvert.DeserializeObject<List<T>>(serializedJson);
Sajed
  • 1,797
  • 2
  • 7
  • 21
  • 1
    get error as operator < cannot be applied to operands of type method groups or Type on line var myDeserializedClass = GetDeserializedList(dresponseMessage); – ZZZSharePoint Feb 03 '22 at 09:31
  • @ZZZSharePoint , You are right, I didn't have tested it in IDE , I think this will work for you. – Sajed Feb 03 '22 at 09:59