我有以下内容:
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);
但是,这不起作用,因为KeyValuePairList
没有使用任何参数调用的构造函数。如果我删除该构造函数,JSON 序列化将失败并出现错误No parameterless constructor found
。我如何知道在其调用中KeyValuePairList
用作KeyValuePair
模板?或者也许我该如何为此目的调整 JSON 序列化程序?
尝试#2
我也试过JSON.net
了,如下:
var oo = JsonConvert.DeserializeObject<KeyValuePairList>(result);
关于如何使这项工作的任何建议?