我有以下幾點:讓JSON反序列化在泛型情況下工作?
public class BaseEntity<T> where T: class
{
public OperationStatus OperationStatus { set; get; }
public List<T> List { set; get; }
protected internal BaseEntity()
{
if (OperationStatus == null)
{
OperationStatus = new OperationStatus();
OperationStatus.IsSuccess = true;
}
this.List = new List<T>();
}
internal BaseEntity(IEnumerable<T> list)
{
if (OperationStatus == null)
{
OperationStatus = new OperationStatus();
OperationStatus.IsSuccess = true;
}
this.List = new List<T>();
foreach (T k in list)
{
this.List.Add(k);
}
}
}
public class KeyValuePair
{
public string key;
public string value;
}
public class KeyValuePairList : BaseEntity<KeyValuePair>
{
public KeyValuePairList() { }
public KeyValuePairList(IEnumerable<KeyValuePair> list)
: base(list) { }
}
// Multiple other classes like KeyValuePair but all have the
// same behavior so they have been derived from BaseEntity
在我的代碼
現在,我試圖JSON字符串映射到KeyValuePair
列表的一個實例,我目前做如下:
result =
@"{
\"d\": {
\"OperationStatus\": {
\"IsSuccess\": true,
\"ErrorMessage\": null,
\"ErrorCode\": null,
\"InnerException\": null
},
\"List\": [{
\"key\": \"Key1\",
"\value\": \"Value1\"
}, {
\"key\": \"Key2\",
\"value\": \"Value2\"
}]
}
}"
嘗試#1
JavaScriptSerializer serializer = new JavaScriptSerializer();
KeyValuePairList output = serializer.Deserialize<KeyValuePairList>(result);
不過,這並不會因爲012的構造工作沒有任何參數調用。如果我刪除該構造函數,則JSON序列化會失敗,並顯示錯誤No parameterless constructor found
。我如何告訴KeyValuePairList
在其調用中使用KeyValuePair
作爲模板?或者,也許我該如何適應JSON序列化程序用於此目的?
嘗試#2
我試過JSON.net
過,具體如下:
var oo = JsonConvert.DeserializeObject<KeyValuePairList>(result);
如何使這項工作有什麼建議?
好的,你的問題,你的解決方案。但是對於我來說,對於一個簡單的json進行反序列化來說代碼太多了。 – 2012-07-09 20:16:52