3

我有以下内容:

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);

关于如何使这项工作的任何建议?

4

2 回答 2

2

实际上,解决方案比我想象的要简单。问题是服务器正在返回带有根节点的 JSON 字符串d。因此,反序列化失败,因为它不知道如何处理根节点d。这可以解决如下:

第 1 步:添加一个额外的 JSONWrapper 类来包装传入的 JSON 字符串:

public class JSONWrapper<T> where T:class
{
    public T d {set; get;}
}

第 2 步:使用这个新类来反序列化

JavaScriptSerializer serializer = new JavaScriptSerializer();
var oo = serializer.Deserialize<JsonWrapper<KeyValuePairList>>(result);

更符合我的整个逻辑,因此我不必进行任何重大更改。感谢所有帮助我度过宝贵时间的人。

于 2012-07-09T20:06:48.517 回答
0

尝试T[]代替List<T>

你应该有两个属性,

public T[] Items{
    get{
        return ItemList.ToArray();
    }
    set{
        ItemList.Clear();
        ItemList.AddRange(value);
    }
}

[ScriptIgnore]
public List<T> ItemList {get;set;}

作为数组的项目将在 JSON 中序列化,您可以使用 ItemList 进行其他操作。

于 2012-07-09T19:20:48.043 回答