Newtonsoft.Json序列化字符串-格式化和时间格式问题
来源:互联网 发布:平面设计软件知乎 编辑:程序博客网 时间:2024/06/09 16:34
最近C#中需要将实体进行json序列化,使用了Newtonsoft.Json
public static void TestJson()
{
DataTable dt = new DataTable();
dt.Columns.Add("Age", Type.GetType("System.Int32"));
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Sex", Type.GetType("System.String"));
dt.Columns.Add("IsMarry", Type.GetType("System.Boolean"));
dt.Columns.Add("Date", Type.GetType("System.DateTime"));
for (int i = 0; i < 4; i++)
{
DataRow dr = dt.NewRow();
dr["Age"] = i + 1;
dr["Name"] = "Name" + i;
dr["Sex"] = i % 2 == 0 ? "男" : "女";
dr["IsMarry"] = i % 2 > 0 ? true : false;
dr["Date"] = DateTime.Now;
dt.Rows.Add(dr);
}
Console.WriteLine(JsonConvert.SerializeObject(dt));
}
但是序列化出来的Json字符串有两个问题
1.没有进行格式化,对使用人员不友好;
2.时间字段形式为数字形式;
查了一下网上对于时间字段建议先转换成字符串,再json序列化,但是发现可以通过自定义时间格式进行json序列化
解决方案如下:
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(JsonConvert.SerializeObject(dt, Formatting.Indented, timeFormat));
这样结果如下:完美解决问题
- Newtonsoft.Json序列化字符串-格式化和时间格式问题
- 表单序列化json字符串和js时间格式化
- Newtonsoft.Json.JsonConvert 序列化日期时间
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json序列化和反序列
- Newtonsoft.Json 转Json字符串为空不序列化
- 前台页面反序列化Newtonsoft.Json序列化的时间问题
- Newtonsoft.Json中的时间格式详解.
- 多线程游戏服务器开发(2)-编写网络库
- 排序——希尔排序
- private public protected slots的区别
- Dynamics CRM 导出系统中实体的属性字段到EXCEL
- 查看系统版本信息
- Newtonsoft.Json序列化字符串-格式化和时间格式问题
- 接口的意义
- Quartz 框架快速入门(四)
- 西蒙iphone-OpenGL ES 教程-04 : 颜色及纹理
- 安卓开发中遇到测试TextView测量宽高
- HDU 1272 小希的迷宫 [并查集]
- I,P,B帧和PTS,DTS的关系
- 设置MySQL开机自动启动的方法
- c标签的使用