.NET & JSON

C# & JSON

DataContractJsonSerializer

// JsonHelper.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace JsonHelper
{
    public class JsonHelper
    {
        /// <summary>
        /// 对象转换成JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonObject">需要格式化的对象</param>
        /// <returns>Json字符串</returns>
        public static string Serialize<T>(T jsonObject)
        {
            DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
            //settings.UseSimpleDictionaryFormat = true;
            //settings.IgnoreExtensionDataObject = true;
            //settings.SerializeReadOnlyTypes = true;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(type: jsonObject.GetType(), settings: settings);
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream: stream, graph: jsonObject);
                stream.Position = 0;
                StreamReader reader = new StreamReader(stream: stream);
                string jsonString = reader.ReadToEnd();
                return jsonString;
            }
        }

        /// <summary>
        /// JSON字符串转换成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString">要转换成对象的JSON字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string jsonString)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(type: typeof(T));
            byte[] buffer = Encoding.UTF8.GetBytes(s: jsonString);
            using (MemoryStream stream = new MemoryStream(buffer: buffer))
            {
                T t = (T)serializer.ReadObject(stream: stream);
                return t;
            }
        }
    }
}

哔了个狗

以上面的 JsonUtil 为例.

using System;
using System.Collections;
using System.Collections.Generic;
using JsonUtil;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JsonHelper.Test
{
    [TestClass]
    public class TestJson
    {
        [TestMethod]
        public void Json1()
        {
            IDictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "张三");
            dict.Add("age", 18);
            dict.Add("birthday", DateTime.Now);
            // 匿名类型序列化报错
            //dict.Add("other", new
            //{
            //    xxx = "xxx"
            //});

            // 嵌套字典类型序列化报错
            var c = new Dictionary<string, object>();
            c.Add("xxx", "xxx");
            dict.Add("other", c);

            string jsonStr = JsonUtil.Serialize(dict);
            if (string.IsNullOrEmpty(jsonStr))
            {
                Assert.Fail();
            }
        }

        [TestMethod]
        public void Json2()
        {
            Hashtable hashtable = new Hashtable();
            hashtable.Add("name", "张三");
            hashtable.Add("age", 18);
            hashtable.Add("birthday", DateTime.Now);

            // 嵌套 Hashtable 可以序列化,但是会多出点奇怪的东西
            Hashtable hashtable2 = new Hashtable();
            hashtable2.Add("xxx", "xxx");
            hashtable.Add("other", hashtable2);

            string jsonStr = JsonUtil.Serialize(hashtable);
            if (string.IsNullOrEmpty(jsonStr))
            {
                Assert.Fail();
            }
        }
    }
}

我只是不想一些库依赖 Newtonsoft.Json 而已,能不能让我好好序列化个JSON.

DataContractJsonSerializer 功能受限,写法繁琐,时不时还来个不能序列化;.NET Core 里干脆连这个类都没了,目前还是采用 Newtonsoft.Json 比较方便.

DataContractJsonSerializer 不支持序列化匿名类型

参考

posted @ 2019-03-07 11:52  taadis  阅读(82)  评论(0编辑  收藏  举报