json.net 反序列化 會不會掛掉的實驗
實驗起源
今天忽然有個疑問 這樣做反序列化 會不會爆炸呢
實驗項目
程式碼如下
public class Order1
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Order2
{
public int Id { get; set; }
}
public class Order3
{
public int Id { get; set; }
public string Name { get; set; }
public int Id1 { get; set; }
public string Name1 { get; set; }
}
public class Order4
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Order5
{
public int Id { get; set; }
public int Name { get; set; }
}
var test = new Order1
{
Id = 1,
Name = "abc"
};
string output = JsonConvert.SerializeObject(test);
//正常
var a1 = JsonConvert.DeserializeObject<Order1>(output);
//缺少Name
var a2 = JsonConvert.DeserializeObject<Order2>(output);
//多出Id1跟Name1
var a3 = JsonConvert.DeserializeObject<Order3>(output);
//Id型別由int轉string
var a4 = JsonConvert.DeserializeObject<Order4>(output);
//反序列化 {}
var a5 = JsonConvert.DeserializeObject<Order1>("{}");
//反序列化 string.Empty
var a6 = JsonConvert.DeserializeObject<Order1>(string.Empty);
//反序列化 null
var a7 = JsonConvert.DeserializeObject<Order1>(null);
//反序列化 abc
var a8 = JsonConvert.DeserializeObject<Order1>("abc");
//反序列化 {a}
var a9 = JsonConvert.DeserializeObject<Order1>("{a}");
//Name型別由sting改int
var a10 = JsonConvert.DeserializeObject<Order5>(output);
實驗結果
正常
{"Id":1,"Name":"abc"}
---------------------------------------------------------
缺少Name
{"Id":1}
---------------------------------------------------------
多出Id1跟Name1
{"Id":1,"Name":"abc","Id1":0,"Name1":null}
---------------------------------------------------------
Id型別由int轉string
{"Id":"1","Name":"abc"}
---------------------------------------------------------
反序列化 {}
{"Id":0,"Name":null}
---------------------------------------------------------
反序列化 string.Empty
null
---------------------------------------------------------
以下會爆炸
反序列化 null
Value cannot be null.
Parameter name: value
---------------------------------------------------------
反序列化 abc
Unexpected character encountered while parsing value: a. Path '', line 0, position 0.
---------------------------------------------------------
反序列化 {a}
Invalid JavaScript property identifier character: }. Path '', line 1, position 2.
---------------------------------------------------------
Name型別由sting改int
Could not convert string to integer: abc. Path 'Name', line 1, position 20.
---------------------------------------------------------
玩實驗
dotnetfiddle.net - Json Net 反序列 實驗室
如果內容有誤請多鞭策謝謝