Newtonsoft.Json 基本用法

本文详细介绍了.NET平台下的开源JSON处理库Newtonsoft.Json的使用方法,包括序列化、反序列化及时间格式自定义等高级功能,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Newtonsoft.Json 是.net 开源的一个json格式处理类库

官方网站:http://json.codeplex.com/

在使用的项目引用Newtonsoft.Json库。平常使用的方法有序列化与反序列方法

 

1 序列化:把一个对象序列化成json格式的字符串

       V_BBSTopic_User entity = db.GetTEntity<V_BBSTopic_User>(sql);
            if (entity != null)
            {
                string json = JsonConvert.SerializeObject(entity);  //序列化
                context.Response.Write(json);
            }

 Newtonsoft.Json 自定义时间格式

  如果不设置时间格式,它默认转为json 的时间格式是这样的:2014-08-29T12:23:234

默认格式明显不是我们想要的,所以必须使用IsoDateTimeConverter类设置时间格式

 IsoDateTimeConverter timeConverter=new IsoDateTimeConverter();
 timeConverter.DateTimeFormat="yyyy-MM-dd HH";
 string strJson = JsonConvert.SerializeObject(entity , Formatting.Indented, timeConverter);

 

 

2 反序列化:主要是把josn格式的字符串转化成一个实体对象。例如

public class A
    {
        public string ID { get; set; }
        public DateTime CreateDate { get; set; }
    }
//反序列化
string json="{'ID':'1','CreateDate ':'2014-08-20'}";
 A a = JsonConvert.DeserializeObject< A>(json);

 

3 Newtonsoft.Json 其它方法

//json 不能是数组
string jsonText2 = "{'a':'aaa','b':'bbb','c':'ccc'}";
JObject jobj = JObject.Parse(jsonText2);
Console.WriteLine("a:"+jobj["a"]);
Console.Read();

 

转载于:https://www.cnblogs.com/jingping/p/3927276.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值