C
C#12mo ago
Rtransat

❔ Get only values when deserialize json

Hi, it's possible to deserialize something like this with only values?
"genres": {
"Action": "Action",
"Adventure": "Aventure",
"Drama": "Drame",
"Fantasy": "Fantastique"
},
"genres": {
"Action": "Action",
"Adventure": "Aventure",
"Drama": "Drame",
"Fantasy": "Fantastique"
},
I would like something like this instead of a Dictionary:
[JsonPropertyName("genres")]
public List<string> Genres { get; set; }
[JsonPropertyName("genres")]
public List<string> Genres { get; set; }
12 Replies
Thinker
Thinker12mo ago
How do you want this to work?
Tinefol
Tinefol12mo ago
Why wouldn't you just deserialize then convert it to list?
Rtransat
Rtransat12mo ago
I'm building an api wrapper. So I just use
[JsonPropertyName("genres")]
public Dictionary<string, string> Genres { get; set; }
[JsonPropertyName("genres")]
public Dictionary<string, string> Genres { get; set; }
And I add some method to get a list?
Thinker
Thinker12mo ago
It's not clear how you want to get a list from this because the json is a dictionary You have "Fantasy": "Fantastique" which isn't obvious how it should become an element in a list.
Rtransat
Rtransat12mo ago
Yes but I only need the values.
Thinker
Thinker12mo ago
Then deserialize into a dictionary and use the Values of the dictionary.
Rtransat
Rtransat12mo ago
Something like this?
[JsonPropertyName("genres")]
private Dictionary<string, string> _Genres { get; set; }

public List<string> Genres => _Genres.Values.ToList();
[JsonPropertyName("genres")]
private Dictionary<string, string> _Genres { get; set; }

public List<string> Genres => _Genres.Values.ToList();
Thinker
Thinker12mo ago
yeah Although personally I'd use IReadOnlyCollection<string> and not List<string>
Rtransat
Rtransat12mo ago
I would like to deserialize _Genres with a private visibility because the users of the lib doesn't need to use _Genres. It's possible? Why not IEnumerable<string>?
arion
arion12mo ago
Wouldn't a DTO to contract map be better in this situation?
Thinker
Thinker12mo ago
might be Corrected myself, having a count is probably beneficial
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.