Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

c# - 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();
}
question from:https://stackoverflow.com/questions/66048601/how-to-allow-configurable-deserialization-of-jobject

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...