简体   繁体   中英

C# make desire Json format

I want to have Json object like this:

In have this code in C#:

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

return JsonConvert.SerializeObject(new { list });

Now my Json is something Like this:

在此输入图像描述

I want to have a Json in this format:

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

You can try creating strings as your JSON objects. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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