How to write a JSON class for the following when the number of fields in "amounts"
is unknown.
{
"amounts": {
"a": 100,
"b": 72
...
...
}
}
- I do understand that
"amounts"
should have been an array, but I’m not
at will to change this. - All children of
"amounts"
are guaranteed to be simple key-value pairs with int values.
Thanks in advance.
2
Answers
You can use
Dictionary<string, ...>
which is quite a common convention among JSON serializers in .NET (at least 2 of the most popular use it – Newtonsoft’s Json.NET and System.Text.Json). For example:P.S.
Depending on serializer/settings used you might need to annotate the property with attribute with property name matching the source json casing.
As Guru Stron already mentioned – you can use
Dictionary<string, int>
for this. However, I believe a cleaner design will be like that:This will let you iterate over the
amounts
easily without being "surprised" by unexpected keys.You can achieve this by creating an
Amount
object with 2 properties –string key
,int value
, and thenamounts
can beList<Amount>
.Besides clean code, this design will help you to add more properties to an "Amount" in future if needed, by simply adding another property to
Amount
class.