我可以反序列化使用的JavaScriptSerializer不可变对象? [英] Can I deserialize to an immutable object using JavascriptSerializer?

查看:79
本文介绍了我可以反序列化使用的JavaScriptSerializer不可变对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Web.Script.Serialization.JavaScriptSerializer

我可以反序列化到一个不可变对象不知何故?

can I deserialize into an immutable object somehow?

   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。

Constraints: I don't want a public empty constructor, I don't want to change everything to mutable, and I don't want to use xml instead of Json.

推荐答案

我必须找到一个这样的答案,因为这是对谷歌的第一个结果,但它并没有举一个例子,我决定分享我想出了(基于由詹姆斯·埃利斯·琼斯提供的链接。)

I had to find an answer for this, and since this is the first result on google, but it didn't give an example, I decided to share what I came up with (based upon the link provided by James Ellis-Jones.)

我的情况是,我需要一个钱的对象是不可改变的。我的钱对象所需的金额和货币。需要为不可变的,因为我使用它,就好像它是十进制值我与(支持像货币值的数学运算)替换它,我需要各地通过它,而不用担心我是否通过引用传递,或对事物的副本

My situation was I needed a "Money" object to be immutable. My Money object needed an amount and a currency. Needs to be immutable because I'm using it as if it were the decimal value I'm replacing it with (math operations supported on like-currency values) and I needed to pass it around without worrying about whether I'm passing by reference or a copy of the thing.

所以,我实现了JavaScriptConverter这里:

So, I implemented the JavaScriptConverter here:

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



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

Then I registered the converter with the JavaScriptSerializer via the web.config file:

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

这就是它!我当时也装点我班有一对夫妇的属性,虽然:

That's it! I did also decorate my class with a couple attributes, though:

[Serializable]
[Immutable]
public class Money

这篇关于我可以反序列化使用的JavaScriptSerializer不可变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆