using 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;
}
}
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.
JavaScriptSerializer provides a customisation API, you can create a class which inherits from JavaScriptConverter to specify how to build your Item class from a dictionary of then use the RegisterConverters method on a JavaScriptSerializer instance to register your custom converter.
definition of javascriptserializer.registerconverters
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.
So, I implemented the JavaScriptConverter here:
Then I registered the converter with the JavaScriptSerializer via the web.config file:
That's it! I did also decorate my class with a couple attributes, though: