【问题标题】:How to convert object list json model?如何转换对象列表json模型?
【发布时间】:2020-07-16 18:34:16
【问题描述】:

我想给前面发送一个JSON模型如下:

这里是:

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

我有从数据库中提取的数据。这是我的对象列表类:

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

我使用此模型填写我的列表并将其作为 JSON 发送到前端。

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

如何创建我最初定义的 JSON 模型?我使用的编程语言是 C# 和 .NET Core。

【问题讨论】:

  • 你试过Dictionary<DateTime,int>吗?
  • 不,我没试过。不知道怎么试?
  • 我不推荐使用 datetime 格式,最好使用 unix 时间戳或模型作为 { datetime:{ "day":22, "month":1, "year":2020 }, data:{} } 将来您将无法将字符串转换为日期时间。

标签: c# json asp.net-core type-conversion jsonconvert


【解决方案1】:

当您将变量放入字典并序列化时,您将获得所需的 JSON。你可以在这里试试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);
    }
}

【讨论】:

  • 如果您只需要日期部分而不是时间,则需要设置 DateFormatStringvar settings = new JsonSerializerSettings() { DateFormatString = "yyyy'-'MM'-'dd" }; var str = JsonConvert.SerializeObject(myDic, settings);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 2020-07-10
  • 2016-10-06
  • 1970-01-01
相关资源
最近更新 更多