C
C#8mo ago
PIE

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:
public class Info
{
[JsonPropertyName("user")]
public User User { get; }
[JsonPropertyName("galleryCount")]
public int GalleryCount { get; }
}

public class User
{
[JsonPropertyName("name")]
public string Name { get; }
[JsonPropertyName("account")]
public int Account { get; }
}
public class Info
{
[JsonPropertyName("user")]
public User User { get; }
[JsonPropertyName("galleryCount")]
public int GalleryCount { get; }
}

public class User
{
[JsonPropertyName("name")]
public string Name { get; }
[JsonPropertyName("account")]
public int Account { get; }
}
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
Jimmacle
Jimmacle8mo ago
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 models
Pobiega
Pobiega8mo ago
You can use Dictionary<string, ...> when you don't know the keys, but do know the value types
PIE
PIEOP8mo ago
I'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...
Jimmacle
Jimmacle8mo ago
are they mostly the same? you could use polymorphic deserialization using that key as the type discriminator
PIE
PIEOP8mo ago
thanks I will look into it o/
Want results from more Discord servers?
Add your server