I have an array of dictionaries, after serializing to JSON I get this string:
"[{"key1":"value1","key2":"value2"}]"
I want to make a List of values out of this JSON, how can I achieve this?
CodePudding user response:
Your JSON is a bit weird, as it's a list with 1 element, that is an object/dictionary... I think you made a mistake with serialization.
But to give you an answer: It's the inverse of what was asked here
Here are System.Text.Json and Json.net examples:
var d = System.Text.Json.JsonSerializer.Deserialize<List<Dictionary<string, string>>>(json);
var d2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(json);
You can then use the List indexer with Dictionary.Values
like
var values = d[0].Values
Note that values
will be a Dictionary<string,string>.ValueCollection
, not a list. But it still has an enumerator.
edit: so you could call Linq's ToList()
.
CodePudding user response:
After you serialization it to a list of dictionaries you can transform it to a list:
var d = System.Text.Json.JsonSerializer.Deserialize<List<Dictionary<string, string>>>(json);
// or Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
List<C> l = d
.SelectMany(x => x.Select(kvp => new C(Key: kvp.Key, Value: kvp.Value)))
.ToList();
C
could look like this:
public record C(string Key, string Value);