我有一個派生自列表的類,無論我做什麼,我都找不到JSON.NET設置值的位置。在我看來,即使是標記的屬性也不會觸發。JSON.NET反序列化不觸發setter
我在所有以下方面設置斷點:
public CartItem Add(int id, int numItems, CARTITEMTYPE type = CARTITEMTYPE.GENERIC)
{
var item = NewByType(type);
item.ID = id;
item.NumItems = numItems;
return this.Add(item);
}
public new CartItem Add(CartItem item)
{
item.Parent = this;
base.Add(item);
return item;
}
public new void AddRange(IEnumerable<CartItem> items)
{
items.Any(f => { f.Parent = this; return true; });
base.AddRange(items);
}
public new void InsertRange(int index, IEnumerable<CartItem> items)
{
items.Any(f => { f.Parent = this; return true; });
base.InsertRange(index, items);
}
public new CartItem Insert(int index, CartItem item)
{
item.Parent = this;
base.Insert(index,item);
return item;
}
但這些都沒有運行反序列化時觸發中斷。
反序列化過程相對簡單,使用這樣的:
public T GetJObject<T>(string cookieName, JsonSerializerSettings jset = null)
{
string cookieContent = Get(cookieName);
return JsonConvert.DeserializeObject<T>(cookieContent, jset);
}
和轉換器類也很簡單:
public class JsonCartConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(CartItem).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get
{
return false;
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
var type = obj["t"] != null ? (CARTITEMTYPE)obj["t"].Value<int>() : CARTITEMTYPE.GENERIC;
var item = CartItems.NewByType(type);
serializer.Populate(obj.CreateReader(), item);
return item;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
}
即使區域標有JsonProperty其他類不被上反序列化打。
[JsonProperty("c")]
public CartItems Children
{
get
{
if (_Children == null) _Children = new CartItems();
if (_Children.Parent == null) _Children.Parent = this;
_Children.SiteID = SiteID;
_Children.UserID = UserID;
return _Children;
}
set
{
Children.Parent = this;
Console.WriteLine("we set the parent");
_Children = value;
}
}
那麼JSON.NET如何對待setter和列表呢?顯然,沒有被擊中?我能強制它達到setter邏輯嗎?
編輯:JSON
[{"t":1,"i":1,"n":4,"r":false,"c":[{"t":5,"i":2,"n":4,"r":false,"c":[]}]},{"t":1,"i":3,"n":4,"r":false,"c":[{"t":5,"i":4,"n":4,"r":false,"c":[{"t":4,"i":6,"n":14,"r":false,"c":[]}]},{"t":1,"i":5,"n":15,"r":false,"c":[]}]}]
因此,它是擊中任何這些:第二個問題是由DBC在這裏找到答案?通過檢查所得到的班級,看起來最後一個例子的制定者沒有受到影響?我從來沒有看到父母得到設置... – dudeinco
它是否使用反射來繞過setter邏輯,並通過將值強制爲私有屬性完全在標準的類中添加/插入功能? – dudeinco
JSON.NET將不會在您的對象上調用任何「添加/插入」方法。 –