C# Model/Entity class for Json Output

What is the correct/standard way to create c# model/entity and a json structure for below image?

C# Model class

public class UnAssignedRequest
{
    public int Total { get; set; }
    public string Subject { get; set; }

}

Existing Json Output

[
  {
    "Total": 0,
    "Subject ": "Physics"
  },
  {
    "Total": 0,
    "Subject ": "Mathamatics"
  },
  {
    "Total": 0,
    "Subject ": "Chemistry"
  },  
  {
    "Total": 8,
    "Subject ": null
  }
]

Here the Total key/value is repeated as 0 with every Subject property which is not at all needed and iam looking for a json format which holds subjects and total of it. which will generate a output like below referred image.

The above json and c# model can also generate a below donut chart but i belive key/value - "total" : 0; on every subject key/value can be avoided and make the json bit efficient by having only one key/value as "Total" : 856; for entire json array, something like below Json.

Desired Json Output :

[
  {
    "Subject ": "Physics"
  },
  {
    "Subject ": "Mathamatics"
  },
  {
    "Subject ": "Chemistry"
  },  
  {
    "Total": 8,    
  }
]

So, how the c# model class need to be for achieve the desired Json Output?

Image Reference

Thanks for sharing your knowledge

Upvotes: 0

Views: 104

Answers (1)

Ivan Khorin
Ivan Khorin

Reputation: 947

using System;
using System.Collections.Generic;
using System.Text.Json;

namespace JsonGenerator
{
    class Item
    {
        public string Subject { get; set; }

        public int? Total { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var items = new List<Item>
            {
                new Item
                {
                    Subject = "Physics"
                },
                new Item
                {
                    Subject = "Mathamatics"
                },
                new Item
                {
                    Subject = "Chemistry"
                },
                new Item
                {
                    Total = 8
                },
            };

            var json = JsonSerializer.Serialize(items, new JsonSerializerOptions { IgnoreNullValues = true, WriteIndented = true });

            Console.WriteLine(json);
        }
    }
}

The trick is in IgnoreNullValues option enabled and int? declarations, that allows to init value type as null.

Result:

[
  {
    "Subject": "Physics"
  },
  {
    "Subject": "Mathamatics"
  },
  {
    "Subject": "Chemistry"
  },
  {
    "Total": 8
  }
]

Upvotes: 1

Related Questions