因為 Json.net 是有附原始碼的,他也附了單元測試的專案,底下是我額外增加的UnitTest,我的目標就是讓底下的測試可以pass,而且原來的Test 也要都能通過。
ValueTypeTest.cs
using System;
using NUnit.Framework;
namespace Newtonsoft.Json.Test {
[TestFixture]
public class ValueTypeTest {
[Test]
public void NullTest() {
string jsonText = JavaScriptConvert.SerializeObject(null);
object obj = JavaScriptConvert.DeserializeObject<Object>(jsonText);
Console.WriteLine(jsonText);
Assert.IsNull(obj);
}
[Test]
public void StringTest() {
string jsonText = JavaScriptConvert.SerializeObject("hello world");
object obj = JavaScriptConvert.DeserializeObject<object>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(obj, "hello world");
}
[Test]
public void IntegerTest() {
string jsonText = JavaScriptConvert.SerializeObject(1234);
int n = JavaScriptConvert.DeserializeObject<int>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(n, 1234);
}
[Test]
public void DateTimeTest() {
string jsonText = JavaScriptConvert.SerializeObject(new DateTime(2007, 7, 22, 12, 4, 55));
DateTime dtime = JavaScriptConvert.DeserializeObject<DateTime>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(dtime, new DateTime(2007, 7, 22, 12, 4, 55));
}
[Test]
public void BooleanTest() {
string jsonText = JavaScriptConvert.SerializeObject(true);
bool bVal = JavaScriptConvert.DeserializeObject<bool>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(bVal, true);
string jsonText2 = JavaScriptConvert.SerializeObject(false);
bool bVal2 = JavaScriptConvert.DeserializeObject<bool>(jsonText2);
Console.WriteLine(jsonText2);
Assert.AreEqual(bVal2, false);
}
[Test]
public void FloatTest() {
string jsonText = JavaScriptConvert.SerializeObject(12345.68F);
float fVal = JavaScriptConvert.DeserializeObject<float>(jsonText);
Console.WriteLine(jsonText);
Assert.AreEqual(fVal, 12345.68F);
}
[Test]
public 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.Error, State.Array, State.Array,State.Error,State.Error },
修改後:
/* Value */{ State.Closed, State.Object,State.Error, State.Error, State.Array, State.Array, State.Error, State.Error },