Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use Json.Net deserialization with immutable classes?

I'm working with an API that uses json. I have some classes that I've created to model the API. To make life easy, my models use public properties, which are in turn used by Json.Net when deserializing the json into objects.

I'd like to make my objects immutable, but I'm running into a problem because if I make my properties read only, I break the deserialization. Is there a way for me to have immutable objects, and use deserialization?

like image 817
GregB Avatar asked Jan 31 '12 19:01

GregB


People also ask

How does JSON deserialization work?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.

How do I use JSON deserializer?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON serialization and deserialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Is polymorphic deserialization possible in system text JSON?

There is no polymorphic deserialization (equivalent to Newtonsoft. Json's TypeNameHandling ) support built-in to System.


2 Answers

Provide a constructor with parameters that correspond to the properties. The casing of the first letters of the parameters and properties does not need to match.

like image 143
Edward Brey Avatar answered Sep 20 '22 09:09

Edward Brey


I think you should be able to use JsonConstructorAttribute. See this question for an example.

like image 31
Matthew Flaschen Avatar answered Sep 20 '22 09:09

Matthew Flaschen