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.

3
  • 1
    have you tried Dictionary<DateTime,int>? Commented Apr 4, 2020 at 16:45
  • No I haven't tried. I don't know how to try? Commented Apr 4, 2020 at 16:46
  • 1
    I don't recommend to use datetime format, best way to use unix timestamp or model as { datetime:{ "day":22, "month":1, "year":2020 }, data:{} } You'll have troublewith converting string to datetime in a future. Commented Apr 4, 2020 at 16:58

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.