skip to Main Content

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


  1. but I’m not at will to change this.

    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:

    public class MyWrapper
    {
        public Dictionary<string, int> Amounts {get; set;}
    } 
    

    P.S.

    Depending on serializer/settings used you might need to annotate the property with attribute with property name matching the source json casing.

    Login or Signup to reply.
  2. As Guru Stron already mentioned – you can use Dictionary<string, int> for this. However, I believe a cleaner design will be like that:

    {
        "amounts": [
            {
                "key": "a",
                "value": 100
            },
            {
                "key": "b",
                "value": 72
            },
            ...
        ]
    }
    

    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 then amounts can be List<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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search