C# 我可以使用JavascriptSerializer反序列化为不可变对象吗?
使用C# 我可以使用JavascriptSerializer反序列化为不可变对象吗?,c#,json,serialization,immutability,C#,Json,Serialization,Immutability,使用System.Web.Script.Serialization.JavaScriptSerializer 我能以某种方式反序列化为不可变对象吗 public class Item { public Uri ImageUri { get;private set; } public string Name { get; private set; } public Uri ItemPage { get;private set; } public decimal
System.Web.Script.Serialization.JavaScriptSerializer
我能以某种方式反序列化为不可变对象吗
public class Item
{
public Uri ImageUri { get;private set; }
public string Name { get; private set; }
public Uri ItemPage { get;private set; }
public decimal Retail { get;private set; }
public int? Stock { get; private set; }
public decimal Price { get; private set; }
public Item(Uri imageUri, string name, Uri itemPage, decimal retail, int? stock, decimal price)
{
ImageUri = imageUri;
Name = name;
ItemPage = itemPage;
Retail = retail;
Stock = stock;
Price = price;
}
}
约束:我不想要一个公共的空构造函数,我不想将所有内容都更改为可变的,我不想使用xml代替Json。JavaScriptSerializer提供了一个定制API,您可以创建一个继承自JavaScriptConverter的类,以指定如何从的字典构建Item类,然后在JavaScriptSerializer实例上使用RegisterConverters方法注册自定义转换器
我必须找到答案,因为这是谷歌的第一个结果,但没有给出一个例子,所以我决定分享我的想法(基于詹姆斯·埃利斯·琼斯提供的链接) 我的情况是,我需要一个“金钱”对象是不变的。我的货币对象需要一个金额和一种货币。需要是不可变的,因为我使用它就像用十进制值替换它一样(类似货币值支持的数学运算),我需要传递它,而不必担心我是通过引用传递还是通过它的副本传递 因此,我在这里实现了JavaScriptConverter:
public class MoneyJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type != typeof(Money))
return null;
var amount = Convert.ToDecimal(dictionary.TryGet("Amount"));
var currency = (string)dictionary.TryGet("Currency");
return new Money(currency, amount);
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var moneyAmount = obj as Money;
if (moneyAmount == null)
return new Dictionary<string, object>();
var result = new Dictionary<string, object>
{
{ "Amount", moneyAmount.Amount },
{ "Currency", moneyAmount.Currency },
};
return result;
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(Money) })); }
}
}
注意,这个对象不是真正不可变的,而是按约定不可变的。未来的开发人员可能会在将来错误地编辑此类,对其中一个字段进行变异,并打破关于不变性的其他假设。将字段设置为只读更具声明性。这降低了未来开发人员意外破坏隐式不可变契约的可能性。您对此有何回答?我也有同样的问题:@DuffMan我不记得=(Jared good point.
不可变的属性是什么?这是你的吗?
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization>
<converters>
<add name="MoneyConverter" type="My.Namespace.MoneyJsonConverter, MyAssembly, Version=1.0.0.0, Culture=neutral"/>
</converters>
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
[Serializable]
[Immutable]
public class Money