Search code examples
c#jsonasp.net-coreserializationjson.net

How to allow configurable deserialization of JObject?


In a .NET Core Console Application I'm calling a REST API that returns JSON. I'm using Newtonsoft.Json.Linq.JObject for deserialization/retrieval of values like this:

string responseJson = await Utils.GetJsonFromApi(apiEndpoint);
dynamic jObject = new Newtonsoft.Json.Linq.JObject();
jObject = NewtonSoft.Json.JsonConvert.DeserializeObject(responseJson);
foreach (var car in jObject.items)
{
    string carId = car.id.ToString();
}

If the API developer changes the array variable items to list or the variable id to code, I will have to update my code and recompile/republish.

Is it possible to leverage app settings somehow, like so:

"carAPI":{
    "uri": "someuri",
    "itemsArrayVariable": "items",
    "carIdVariable": "id" 
}

And use these settings in my API client something like this:

foreach (var car in jObject.itemsArrayVariable)
{
    string carId = car.carIdVariable.ToString();
}

Solution

  • Deserialize into a Dictionary<string, JToken> and dive into your data recursively. How to do so is documented in other Q&As.

    But you shouldn't do this, it will make your code unmaintainable. API developers should not make such breaking changes, and you shouldn't prepare your code for in case they do this anyway. It's what API versioning is for.

    This solution also isn't going to work if they're going to move the data to a deeper or higher level in the JSON, and so on. You would have to recompile anyway, and they should do a change like that on another endpoint anyway, allowing old clients to keep working.