Attempting to get value from different JSON files with variable key
Hello o/ I am attempting to deserilize and obtain the value from a variety of JSON files that contain similar values, but different keys with System.Text.Json.
This was the current classes that I used in order to extract the values for one JSON file:
I know it's not possible to directly set attributes with a variable, but is there another way of dynamically searching for a value besides creating a class for every case?
Thanks!
6 Replies
if it's truly completely dynamic you can parse it into a
JsonDocument
but if you know ahead of time the schemas you're working with i'd just make normal modelsYou can use
Dictionary<string, ...>
when you don't know the keys, but do know the value typesI'm not sure what you mean by normal models, is it the same as the classes that I used above?
Also there is an identifier from the JSON file that all have the same key that denotes the type of the JSON (all the JSON files with a "tumber" identifier will have the same keys). I could use it with a switch statement in order to parse preset keys in order to get the correct values as you said but I'm wondering if there is a better way...
are they mostly the same? you could use polymorphic deserialization using that key as the type discriminator
How to serialize properties of derived classes with System.Text.Jso...
Learn how to serialize polymorphic objects while serializing to and deserializing from JSON in .NET.
thanks I will look into it o/