I know there's an attribute to handle private setters but I kind of want this behavior as a default, is there a way to accomplish this? Except tweaking the source. Would be great if there was a setting for this.
Private setter means the variable can be set inside the class in which it is declared in. It will behave like readonly property outside that class's scope.
Use private set when you want setter can't be accessed from outside. Use readonly when you want to set the property only once. In the constructor or variable initializer.
This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Types. public class Videogame { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }
I came here looking for the actual attribute that makes Json.NET populate a readonly property when deserializing, and that's simply [JsonProperty]
, e.g.:
[JsonProperty] public Guid? ClientId { get; private set; }
Just provide a constructor that has a parameter matching your property:
public class Foo { public string Bar { get; } public Foo(string bar) { Bar = bar; } }
Now this works:
string json = "{ \"bar\": \"Stack Overflow\" }"; var deserialized = JsonConvert.DeserializeObject<Foo>(json); Console.WriteLine(deserialized.Bar); // Stack Overflow
I prefer this approach where possible since:
{ get; private set; }
and just { get; }
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With