C# Json

C# 使用Newtonsoft.Json处理JSON
这篇博客介绍了如何在C#中使用Newtonsoft.Json库来解析和序列化JSON数据,包括JsonApi的使用和最佳实践。

Json Api的参考
https://www.newtonsoft.com/json

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class Test
{
    public static void Main()
    {
        Product product = new Product();
        product.ExpiryDate = new DateTime(2008, 12, 28);

        JsonSerializer serializer = new JsonSerializer();
        serializer.Converters.Add(new JavaScriptDateTimeConverter());


        serializer.NullValueHandling = NullValueHandling.Ignore;

        using (StreamWriter sw = new StreamWriter(@"D:\json.txt"))
        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            serializer.Serialize(writer, product);
            // {"ExpiryDate":new Date(1230375600000),"Price":0}

            // without the converters 
            // {"ExpiryDate":"2008-12-28T00:00:00"} 
        }

        using (StreamReader sr = new StreamReader(@"D:\json.txt"))
        using (JsonReader reader = new JsonTextReader(sr))
        {
            var item = serializer.Deserialize<Product>(reader);
            //这里使用泛型方法是必要的,不然
            //Product? p = item as Product;

            if (item!= null)
            {
                Console.WriteLine(item.ExpiryDate);
            }
        }



    }




 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值