You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
JsonSerializer support for immutable classes and structs. #29895
It would be very helpful if JsonSerializer supported immutable classes/structs like that, especially since Newtonsoft Json.NET supports deserialization through the constructor.
However there are a few issues surrounding immutable types:
Constructor parameter names are usually camelCase while Properties are PascalCase. One way to solve this is by setting JsonSerializerOptions.PropertyNameCaseInsensitive in to true. Another way is to use the Deconstruct-pattern introduced in C# 7.0, instead of Properties for serialization.
There may be several constructors (and Deconstruct methods). So it's not always clear which to use. Newtonsoft Json.NET uses a JsonConstructorAttribute.htm, which has the disadvantage that the data objects need to know about serialization.
Constructor parameters, properties and Deconstruct method parameters might not match up, possibly leading to confusing situations where deserializing a previously serialized object does not work.
Immutable structs always still have a default parameterless constructor.
Reacted by Ganbarukamo41, Viktor Svub, Simon Cropp, Timo van Zijll Langhout, Tommy Long, RyanG, Robert Schmidt, Vladislav Timakov, Logan Dam, Cihan Yakar and 40 more
changed the title [-]`JsonSerializer` support for immutable `class`es and `struct`s.[/-][+]JsonSerializer support for immutable classes and structs.[/+]on Jun 15, 2019
This is a known limitation of the System.Text.Json serializer for v1. We plan to support this in the future.
Reacted by Emil Petro, Robert Schmidt, Chad Edrupt, Bernard Vander Beken, Mertsch, Brandon Minnick, Mehdi Dehghani, Oblomoff, Cédric Royer-Bertrand, Davilink and 11 more
Reacted by Robert Schmidt, Chad Edrupt, Bernard Vander Beken, Mertsch, Oblomoff, Pavel, Nate Barbettini, Martin Lindgren, yxrkt, John Hamm and 1 more
I totally was going to write an issue about this, glad I noticed this before that 🙃
I personally thought that writing a private setter on otherwise a readonly property purely because of JSON (de)serialization is kind of hacky. I know that I could write a custom converter (when it's implemented) or use a constructor (which I remember will be supported soon? I could be wrong) but... that's effort ☺️
For the 3.0 release, there is no planned additional support for calling a non-default constructor during deserialization. That would have to be done by a custom converter.
staticvoidMain(string[]args){varobj=newResponse(true,"Hi"){ResponseCode=100};varjson=System.Text.Json.JsonSerializer.Serialize(obj);// System.NotSupportedException: 'Deserialization of reference types without parameterless constructor is not supported.varresponse=System.Text.Json.JsonSerializer.Deserialize<Response>(json);Console.WriteLine(response.Message);}publicclassResponse{publicboolIsSuccess{get;set;}publicstringMessage{get;set;}publicintResponseCode{get;set;}publicResponse(boolisSuccess=false,stringmessage=""){IsSuccess=isSuccess;Message=message;}}
Response class is considered not having a parameterless constructor, but actually it does use default values for parameters, that can be used just like a parameterless constructor, like this:
vartest=newResponse();
Could the new JSON API check if the constructor parameters have default values before consider it not paremeterless?
Reacted by Oleksii Holub, Pierre Arnaud, Bernard Vander Beken, Will Dean, danila polevshchikov, Matthias Fussenegger, Philip Daubmeier, NN, Saengea and Peter Riesz
I missed the Newtonsoft.Json the nice attribute JsonConstructor that is very handy when serializing classes that do not expose public constructor.. like the one below...
public class Envelope<T>
{
public T Result { get; }
public string ErrorMessage { get; }
public DateTime TimeGenerated { get; }
[JsonConstructor] // This constructor is marked as the valid JsonConvert constructor for JsonConvert.DeserializeObject usage.
protected internal Envelope(T result, string errorMessage)
{
Result = result;
ErrorMessage = errorMessage;
TimeGenerated = DateTime.UtcNow;
}
}
public sealed class Envelope : Envelope<string>
{
private Envelope(string error)
: base(null, error)
{
}
public static Envelope Ok() => new Envelope(null);
public static Envelope<T> Ok<T>(T result) => new Envelope<T>(result, default);
public static Envelope Error(string error) => new Envelope(error);
public static Envelope<T> Error<T>(T result) => new Envelope<T>(result, default);
public static Envelope<T> Error<T>(T result, string error) => new Envelope<T>(result, error);
}
Activity
[-]`JsonSerializer` support for immutable `class`es and `struct`s.[/-][+]JsonSerializer support for immutable classes and structs.[/+]ahsonkhan commentedon Jun 18, 2019
This is a known limitation of the
System.Text.Jsonserializer for v1. We plan to support this in the future.steveharter commentedon Jun 18, 2019
You can write a custom converter for this.
Gnbrkm41 commentedon Jun 19, 2019
I totally was going to write an issue about this, glad I noticed this before that 🙃
I personally thought that writing a private setter on otherwise a readonly property purely because of JSON (de)serialization is kind of hacky. I know that I could write a custom converter (when it's implemented) or use a constructor (which I remember will be supported soon? I could be wrong) but... that's effort☺️
steveharter commentedon Jun 19, 2019
For the 3.0 release, there is no planned additional support for calling a non-default constructor during deserialization. That would have to be done by a custom converter.
Gnbrkm41 commentedon Jun 19, 2019
That's fine, as long as it's in the plan in some way... One step at a time 😁
khellang commentedon Oct 22, 2019
There's a fair bit of overlap with this issue and https://github.com/dotnet/corefx/issues/38569.
Gnbrkm41 commentedon Oct 22, 2019
@khellang, it probably overlaps because this issue is dotnet/corefx#38569 😄 I guess you meant 41973?
khellang commentedon Oct 22, 2019
LOL, no, I meant https://github.com/dotnet/corefx/issues/40399 😂
Mike-E-angelo commentedon Oct 22, 2019
😅
danstur commentedon Nov 15, 2019
@ahsonkhan Is there work currently being done on this issue? If not, is this something where a pull request would be considered?
git-net commentedon Nov 23, 2019
seems would support Deserialize anonymous object?
layomia commentedon Nov 25, 2019
From @endeffects in dotnet/corefx#40399:
ahsonkhan commentedon Nov 25, 2019
From @EdiWang in https://github.com/dotnet/corefx/issues/41102:
Work around JsonSerializer limitation.
manne commentedon Jan 15, 2020
I have started to implement a custom converter for
immutabletypes here https://github.com/manne/obviously/tree/master/src/system.text.json.The converter is able to read "basic" types. The type must have exactly one constructor with at least one parameter. The type has not be sealed.
Example
I have uploaded a nuget package Obviously.System.Text.Json, it is not yet indexed.
Feedback and PRs are always welcome 😉
ahsonkhan commentedon Jan 25, 2020
From @ahedreville in #1925:
System.Text.Json: add parameterless constructor (#10)
Add some custom converters as a hack to get serialization/deserializa…
Support for persistence to EventStoreDB. Fixes #3 (#4)