1

I want to send a JSON model to the front as follows:

Here it is:

{
    "2020-01-22":1,
    "2020-01-23":2,
    "2020-01-24":3,
    ..
}

I have data that I pulled through the database. Here is my class for the list of objects:

public class MyClass
{
    public string DateTime { get; set; }
    public int? Data { get; set; }
}

I fill my list using this model and send it to the front side as JSON.

{
   "dateTime": "2020-01-22",
   "data": 1
},
{
   "dateTime": "2020-01-23",
   "data": 2
}, 
    ..

How can I create the JSON model I originally defined? The programming language I use is C# and .NET Core.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Muhammed Caylak
  • 339
  • 1
  • 4
  • 15

1 Answers1

1

When you put your variables in Dictionary and serialize you will get the JSON you want. You can try it here https://dotnetfiddle.net/dmepqX

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
    public static void Main()
    {
        var myDic = new Dictionary<DateTime,int>();
        myDic.Add(DateTime.Now,1);
        var str = JsonConvert.SerializeObject(myDic);
        Console.WriteLine(str);
    }
}
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
  • You'll need to set the `DateFormatString` if you only want the date part and not the time: `var settings = new JsonSerializerSettings() { DateFormatString = "yyyy'-'MM'-'dd" }; var str = JsonConvert.SerializeObject(myDic, settings);` – Brian Rogers Apr 24 '20 at 19:58