gpt4 book ai didi

c# - 我可以使用 JavascriptSerializer 反序列化为不可变对象(immutable对象)吗?

转载 作者:太空狗 更新时间:2023-10-30 00:46:07 26 4
gpt4 key购买 nike

使用 System.Web.Script.Serialization.JavaScriptSerializer

我能以某种方式反序列化为不可变对象(immutable对象)吗?

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

约束:我不想要一个公共(public)的空构造函数,我不想将所有内容都更改为可变的,我不想使用 xml 而不是 Json。

最佳答案

我必须为此找到答案,因为这是谷歌上的第一个结果,但它没有给出示例,我决定分享我的想法(基于 James Ellis 提供的链接-琼斯。)

我的情况是我需要一个不可变的“Money”对象。我的 Money 对象需要金额和货币。需要是不可变的,因为我正在使用它,就好像它是我要替换它的十进制值(类似货币值支持的数学运算),我需要传递它而不用担心我是否通过引用传递或东西的副本。

所以,我在这里实现了 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) })); }
}
}

然后我通过 web.config 文件向 JavaScriptSerializer 注册了转换器:

<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

关于c# - 我可以使用 JavascriptSerializer 反序列化为不可变对象(immutable对象)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4080644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com