tests/DotNetCommon.Test/Serialize/DiffNewtonsoftAndSystemTextJson.cs

(开头部分) 16KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

using DotNetCommon.Extensions;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Shouldly;
using System;
using System.Data;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace DotNetCommon.Test.Serialize
{
    [TestFixture]
    internal class DiffNewtonsoftAndSystemTextJson
    {
        class Demo
        {
            public int? Num { get; set; }
        }

        /// <summary>
        /// SystemTextJson 无法 "" => int? 无法转为null
        /// </summary>
        [Test]
        public void Test()
        {
            var str = "{\"Num\":\"\"}";
            var d = Newtonsoft.Json.JsonConvert.DeserializeObject<Demo>(str);
            d.Num.ShouldBe(null);

            try
            {
                System.Text.Json.JsonSerializer.Deserialize<Demo>(str);
            }
            catch (Exception ex)
            {
                ex.Message.ShouldBe("The JSON value could not be converted to System.Nullable`1[System.Int32]. Path: $.Num | LineNumber: 0 | BytePositionInLine: 9.");
            }

            //兼容了
            var d2 = str.ToObject<Demo>();
            d2.Num.ShouldBe(null);
        }

        class Demo2
        {
            public int Num { get; set; }
        }
        /// <summary>
        /// 均无法 null 或 "" => int
        /// </summary>
        [Test]
        public void Test2()
        {
            var str = "{\"Num\":null}";
            try
            {
                Newtonsoft.Json.JsonConvert.DeserializeObject<Demo2>(str);
            }
            catch (Exception ex)
            {
后面还有 433 行代码,解锁后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。