C# serialize datetime then deserialize, print lose precision. resolve by ToString("o")

//Service
namespace WebApplication4.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set;  }
        public string Author { get; set;  }
        public string Abstract { get; set; }
        public string Comment { get; set;  }    
        public string Content { get; set;  }
        public string Summary {  get; set; }
        public DateTime Time { get; set; }
        public string Title {  get; set; }
        public string Topic { get; set;  }
    }
}

using WebApplication4.Models;

namespace WebApplication4.Services
{
    public class BookService
    {
        private List<Book> booksList {  get; set; }
        public BookService()
        {
        }

        public List<Book> GetBooksList(int len = 10000)
        {
            booksList = new List<Book>();
            for (int a = 1; a < len + 1; a++)
            {
                booksList.Add(new Book()
                {
                    Id = a,
                    Name = $"Name_{a}",
                    ISBN = $"ISBN_{a}_{Guid.NewGuid():N}",
                    Abstract = $"Abstract_{a}",
                    Author = $"Author_{a}",
                    Comment = $"Comment_{a}",
                    Content = $"Content_{a}",
                    Summary = $"Summary_{a}",
                    Time = DateTime.Now,
                    Title = $"Title_{a}",
                    Topic = $"Topic_{a}"
                });
            }
            return booksList;
        }

        public Book? GetBooksById(int id)
        {
            return booksList.Where(x => x.Id == id)?.FirstOrDefault();
        }

    }
}
using Microsoft.AspNetCore.Mvc;
using WebApplication4.Models;
using WebApplication4.Services;

namespace WebApplication4.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class BookController : Controller
    {
        BookService bkService;
        public BookController(BookService bkServiceValue)
        {
            bkService = bkServiceValue;
        }
        [HttpGet("GetBooks")]
        [HttpGet("GetBooks2", Name = "GetBooks3")]
        [HttpGet("GetBooks4")]
        [HttpGet("GetBooks5")]
        [HttpGet("GetBooks6")]
        [HttpGet("GetBooks7")]
        public List<Book> GetBooks()
        {
            return bkService.GetBooksList();
        }

        [HttpGet("GetBook/{id}")]
        public Book? GetBookById(int id)
        {
            return bkService.GetBooksById(id);
        }         
    }
}

using WebApplication4.Controllers;
using WebApplication4.Services;

namespace WebApplication4
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
            builder.Services.AddOpenApi();
            builder.Services.AddSingleton<BookService>();
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.MapOpenApi();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}


//client
using Newtonsoft.Json;

namespace ConsoleApp10
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await GetBooksAsync();
        }

        static async Task GetBooksAsync()
        {
            string bookUrl = "https://localhost:7129/api/book/GetBooks2";
            using (HttpClient client = new HttpClient())
            {
                string jsonStr = await client.GetStringAsync(bookUrl);
                List<Book>? bksList=JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if (bksList != null && bksList.Any())
                {
                    foreach(var bk in bksList)
                    {
                        Console.WriteLine($"Id:{bk.Id},time:{bk.Time}");
                    }
                }
            }
        }


        public class Book
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string ISBN { get; set; }
            public string Author { get; set; }
            public string Abstract { get; set; }
            public string Comment { get; set; }
            public string Content { get; set; }
            public string Summary { get; set; }
            public DateTime Time { get; set; }
            public string Title { get; set; }
            public string Topic { get; set; }
        }
    }
}

 

Console.WriteLine($"Id:{bk.Id},time:{bk.Time}");
"time":"2026-03-21T00:06:56.4686857+08:00"
Id:1,time:2026-03-21 00:06:56

 

 

Console.WriteLine($"Id:{bk.Id},time:{bk.Time.ToString("O")}");
"time":"2026-03-21T00:07:57.6253803+08:00"
Id:1,time:2026-03-21T00:07:57.6253803+08:00

 

posted @ 2026-03-21 00:08  FredGrit  阅读(12)  评论(0)    收藏  举报