-2

my requirement is to dynamically map the json to C# model using newtonsoft.json or any other.

Let say i have these classes in my C# project.

ModelA {string FirstName} ModelB{int DepartmentId}

so if i get json as {"FirstName":"John"}, it should resolve to ModelA object. likewise for json {"DepartmentId":8}, it should resolve to ModelB

var model = JsonConvert.DeserializeObject<**What should come here as i want this dynamic**>(**Json for ModelA or ModelB**);

How to acheive this?

Editing question. Thanks Guru for solutuon.

the other part of requirement is the model i will resolve from json, i need to pass the type of resolved Model to the generic method as below (i.e. in place of T where T is class). How to do this. _unitOfWork.Repository <T where T is class>.Add(modelA)

doing something like Type type = typeof(modelA) and then doing unitOfWork.Repository <type>.Add(modelA) gives error type is variable but is used like type Please help. looking this for long time. could not find satisfying solution anywhere.

Dev
  • 93
  • 8
  • 3
    You will need a custom `JsonConverter` that checks for the presence of the appropriate property and deserializes to that model. See [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182) for how. – dbc Oct 09 '21 at 19:37
  • Does [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182) answer your question sufficiently, or do you need more precise help? If so, where are you confused? – dbc Oct 09 '21 at 20:03
  • 1
    Thanks for quick reply Guru. Will try the solutions in the link you provided and post here the results. – Dev Oct 09 '21 at 20:04

1 Answers1

2

Using custom converter usually is a preferable option but if you need just to parse those two models in some cases you can take "shortcut" version and parse json to JObject and convert it into an object "on the spot":

public class ModelA
{
    public string FirstName { get; set; }
}
public class ModelB
{
    public int DepartmentId { get; set; }
}

var json_str = "{\"FirstName\":\"John\"}";
var jObject = JObject.Parse(json_str);
if (jObject.ContainsKey("FirstName"))
{
    var a = jObject.ToObject<ModelA>();
    Console.WriteLine(a.FirstName);
}
else if(jObject.ContainsKey("DepartmentId"))
{
    var b = jObject.ToObject<ModelB>();
    Console.WriteLine(b.DepartmentId);
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thanks Guru for solution. Have edited question for next part of requirement. How will all this work if i have around 100 models – Dev Oct 10 '21 at 05:24
  • @Pankaj TBH it should be a separate question. Also I don't understand why do you need such handling - you can call required method with correct generic type parameters inside `if` statements. – Guru Stron Oct 11 '21 at 12:25