我正在使用JavascriptSerializer
这样的自定义JavascriptConverter
:
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
SomeObjectModel TheObject = obj as SomeObjectModel;
Dictionary<string, object> OutputJson = new Dictionary<string, object>();
OutputJson.Add("SomeKey", SomeObjectModel.SomeProperty);
return OutputJson;
}
现在我希望能够在运行时动态更改SomeKey
所以我想创建一个键字典,将这个字典传递给序列化程序,然后执行以下操作:
OutputJson.Add(TheJsonDictionary.SomeKey, SomeObjectModel.SomeProperty);
但是,当我向函数调用添加一个参数时,如下所示:
public override IDictionary<string, object> Serialize(Dictionary<string, string> TheJsonDictionary, object obj, JavaScriptSerializer serializer)
我在编译时收到错误消息。现在我知道为什么我得到这个错误(抽象方法定义了2个参数,我传递了3个)我想知道如何解决这个问题,以便我可以传入一个字典来对密钥进行编码。 / p>
感谢。
答案 0 :(得分:4)
我想唯一的解决方法是继承JavaScriptSerializer
并重新实现Serialize
方法以接受任意TheJsonDictionary
字典:
class CustomJavaScriptSerializer : JavaScriptSerializer
{
public Dictionary<string, string> TheJsonDictionary { get; private set; }
public string Serialize(object obj, Dictionary<string, string> TheJsonDictionary = null)
{
this.TheJsonDictionary = TheJsonDictionary;
return base.Serialize(obj);
}
}
现在,在您的自定义转换器中,您可以将序列化程序对象强制转换回CustomJavaScriptSerializer
并获取自定义关键字:
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var TheJsonDictionary = (serializer as CustomJavaScriptSerializer).TheJsonDictionary;
// rest of method
}
答案 1 :(得分:1)
据我所知,这就是你所需要的:
class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, string>();
//dict.Add("SomeKey", "SomeProperty1");
dict.Add("SomeKey", "SomeProperty2");
var myConverter = new MyConverter();
var serialized = myConverter.Serialize(dict, new SomeObjectModel() { SomeProperty1 = 1, SomeProperty2 = 2 }, new MySerializer());
}
class MySerializer : JavaScriptSerializer
{ }
class MyConverter : JavaScriptConverter
{
Dictionary<string, string> _theJsonDictionary;
public IDictionary<string, object> Serialize(Dictionary<string, string> TheJsonDictionary, object obj, JavaScriptSerializer serializer)
{
_theJsonDictionary = TheJsonDictionary;
return Serialize(obj, serializer);
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
SomeObjectModel TheObject = obj as SomeObjectModel;
Dictionary<string, object> OutputJson = new Dictionary<string, object>();
foreach (var item in _theJsonDictionary.Keys)
{
OutputJson.Add(item, TheObject.GetType().GetProperty(_theJsonDictionary[item]).GetValue(TheObject));
}
return OutputJson;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
return new object();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(object) }.AsEnumerable(); }
}
}
class SomeObjectModel
{
public int SomeProperty1 { get; set; }
public int SomeProperty2 { get; set; }
}
}