C
C#2y 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
Thinker2y ago
How do you want this to work?
Tinefol
Tinefol2y ago
Why wouldn't you just deserialize then convert it to list?
Rtransat
RtransatOP2y 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
Thinker2y 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
RtransatOP2y ago
Yes but I only need the values.
Thinker
Thinker2y ago
Then deserialize into a dictionary and use the Values of the dictionary.
Rtransat
RtransatOP2y 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
Thinker2y ago
yeah Although personally I'd use IReadOnlyCollection<string> and not List<string>
Rtransat
RtransatOP2y 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
arion2y ago
Wouldn't a DTO to contract map be better in this situation?
Thinker
Thinker2y ago
might be Corrected myself, having a count is probably beneficial
Accord
Accord2y 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.

Did you find this page helpful?