0

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)

4
  • Replace T with the class that you are expecting. You should know which schema you are expecting depending on the request's route, parameters, content, and headers. Commented Apr 18, 2022 at 11:39
  • That is the question i dont know the schema before reading the data Commented Apr 18, 2022 at 11:48
  • Does your schema allow for properties that are null can be excluded from the result? That would still make this one schema. Commented Apr 18, 2022 at 11:53
  • you can deserialize to a JObject, and then inspect the properties and act acordingly Commented Apr 18, 2022 at 12:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.