因為 Json.net 是有附原始碼的,他也附了單元測試的專案,底下是我額外增加的UnitTest,我的目標就是讓底下的測試可以pass,而且原來的Test 也要都能通過。
ValueTypeTest.cs
using System;
using NUnit.Framework;
namespace Newtonsoft.Json.Test {
[TestFixture]
public class ValueTypeTest {
[Test]
void NullTest() {
string jsonText = JavaScriptConvert.SerializeObject(null);
object obj = JavaScriptConvert.DeserializeObject<Object>(jsonText);
Console.WriteLine(jsonText);
Assert.IsNull(obj);
}
[Test]
void StringTest() {
string jsonText = JavaScriptConvert.SerializeObject("hello world");
object obj = JavaScriptConvert.DeserializeObject<object>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(obj,"hello world");
}
[Test]
void IntegerTest() {
string jsonText = JavaScriptConvert.SerializeObject(1234);
int n = JavaScriptConvert.DeserializeObject<int>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(n,1234);
}
[Test]
void DateTimeTest() {
new DateTime(2007,7,22,12,4,55));
DateTime dtime = JavaScriptConvert.DeserializeObject<DateTime>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(dtime,void BooleanTest() {
true);
bool bVal = JavaScriptConvert.DeserializeObject<bool>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(bVal,255);">string jsonText2 = JavaScriptConvert.SerializeObject(false);
bool bVal2 = JavaScriptConvert.DeserializeObject<bool>(jsonText2);
Console.WriteLine(jsonText2);
Assert.AreEqual(bVal2,255);">false);
}
[Test]
void FloatTest() {
string jsonText = JavaScriptConvert.SerializeObject(12345.68F);
float fVal = JavaScriptConvert.DeserializeObject<float>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(fVal,12345.68F);
}
[Test]
void EnumTest() {
string jsonText = JavaScriptConvert.SerializeObject(StoreColor.White);
StoreColor color = JavaScriptConvert.DeserializeObject<StoreColor>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(color,StoreColor.White);
}
}
}
開始看code後,發現比想像中的簡單,失敗的原因是作者有檢查且擋掉,或許這不是 bug 而是 by design 吧
JsonSerializer.cs,line:406-407
修改前:
if (value == null)
throw new ArgumentNullException("value");
修改後:
//if (value == null)
// throw new ArgumentNullException("value");
JsonWriter.cs,line104
修改前:
/* Value */{ State.Error,State.Object,State.Error,State.Array,State.Error },
修改後:/* Value */{ State.Closed,