Home > front end >  How to map model class with different json from an api
How to map model class with different json from an api

Time:04-19

I am calling an external API, which is returning me JSON data but with 3 different schema.

I have created 3 model class

public class Test1
{
  string Name {get;set;}
  int age {get;set;}
}

public class Test2
{
  int sal {get;set;}
  int age {get;set;}
}

public class Test3
{
  string Name {get;set;}
  int age {get;set;}
  bool Valid {get;set;}
}

My question is how would I do the deserialization to that object class from json without reading the data first as I am dont know what will be the correct schema?

i.e Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json)

CodePudding user response:

You can use Newtonsoft.Json.Linq.JToken object for json strings that you not know the schema.

using Newtonsoft.Json.Linq;

string jsonObj = "{'MyKey':'MyValue'}";

string jsonArr = "[{'MyKey':'MyValue'}, {'MyKeyAtOtherItem':'MyValue1'}]";

string primitiveArray = "['A','B','C']";

var tokenFromObj = JToken.Parse(jsonObj);
var tokenFromArray = JToken.Parse(jsonArr);
var tokenFromPrimitiveArray = JToken.Parse(primitiveArray);

Console.WriteLine("Array Explore Start");
ExploreJson(tokenFromArray);

Console.WriteLine("Object Explore Start");
ExploreJson(tokenFromObj);

Console.WriteLine("Primitive Explore Start");
ExploreJson(tokenFromPrimitiveArray);

void ExploreJson(JToken token)
{
    if (token is JArray)
    {
        var array = token as JArray;
        for (int i = 0; i < array.Count(); i  )
        {
            var item = array[i];
            Console.WriteLine($"Exploring properties of {i}");
            ExploreJson(item);
        }
    }
    else if (token is JObject)
    {
        var jObj = token as JObject;
        foreach (var item in jObj)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
    Console.WriteLine(token.ToString());
}

If you now the (at least) the schema is array or a single object you can use JObject.Parse or JArray.Parse functions.

  • Related