{
"TestObjects": [
{"the": "goal"},
{"is": "to"},
{"deserialize": "this"},
{"simple": "array"},
{"of": "objects"},
{"into": "a"},
{"C#": "Dictionary"}
]
}
Using .NET System.Text.Json. Seeking methodology to deserialize an array of objects where each object has two strings, as shown above, into a Dictionary<string, string>.
I have seen answers that describe deserializing into Dictionary<string, string>[]
whereby each object is placed in a distinct Dictionary<string, string>
, and that works. E.g. Ten objects results in an array of ten dictionaries. Example below works:
public class TestClass
{
public Dictionary<string, string>[] TestObjects { get; set; }
}
var stream = File.OpenRead(@"C:testtest.json");
TestClass result = JsonSerializer.Deserialize<TestClass>(stream);
So, referring to the above example that works, the goal is to deserialize into a C# property of the form
Dictionary<string, string> TestObjects { get; set; }
as opposed to
Dictionary<string, string>[] TestObjects { get; set; }
Thank You
3
Answers
you can convert an array to a dictionary
But remember the dictionary shoud have the unique keys, otherwise you will get an exception
or if you want to deserialize to a class, you will need to write a json converter
In order for it to deserialize as a Dictionary, it would have to be in this format:
You could, however, add another read-only property that converts the array of dictionaries into one dictionary.
You could use a simple converter.
Decorate the Property with
[JsonConverter(...)]
:The custom converter reads each property and value from the array of objects and uses them as the Key and Value of a Dictionary.
It’s assumed that all keys (Properties) have a different name.
When the
Utf8JsonReader
gets to the end of the arrays, i.e., when[Utf8JsonReader].TokenType == JsonTokenType.EndArray
, return the Dictionary:Note: there’s no real error checking here. I leave it to you, since you know what the real JSON contains.