繁体   English   中英

C#make渴望Json格式

[英]C# make desire Json format

我想要像这样的Json对象:

在C#中有这个代码:

var list = new ArrayList();
foreach (var item in stats)
{
    list.Add(new { item.date.Date, item.conversions });
}

return JsonConvert.SerializeObject(new { list });

现在我的Json是这样的:

在此输入图像描述

我想要这种格式的Json:

//{01/21/2017,14}
//{01/22/2017,17}
//{01/23/2017,50}
//{01/24/2017,0}
//{01/25/2017,2}
//{01/26/2017,0}

您可以尝试创建字符串作为JSON对象。 例如:

var list = new List<string>();
foreach (var item in stats)
     {
         list.Add(String.Format("{0},{1}",item.date.Date, item.conversions));
     }

return JsonConvert.SerializeObject(new { list });

//I haven't tested the code.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestsJson
{
    class Model
    {
        public DateTime Date { get; set; }

        public int Clicks { get; set; }

        public Model(DateTime date, int clicks)
        {
            Date = date;
            Clicks = clicks;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var data = new List<Model>()
            {
                new Model(new DateTime(2017, 01, 21), 14),
                new Model(new DateTime(2017, 01, 22), 17),
                new Model(new DateTime(2017, 01, 23), 50),
                new Model(new DateTime(2017, 01, 24), 0),
                new Model(new DateTime(2017, 01, 25), 2),
                new Model(new DateTime(2017, 01, 26), 0)
            };

            foreach (var model in data)
            {
                var json = "{" + JsonConvert.SerializeObject(model.Date.ToShortDateString()) + ":" + model.Clicks + "}";
                Console.WriteLine(json);
            }

            Console.Read();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM