Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private setters in Json.Net

Tags:

c#

json.net

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.

like image 324
Daniel Avatar asked Nov 01 '10 06:11

Daniel


People also ask

What is a private setter?

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.

Why do we use private sets?

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.

What is JsonProperty C#?

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


1 Answers

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

Alternative Solution

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:

  • It doesn't require you to decorate your properties with attributes.
  • It works with both { get; private set; } and just { get; }.
like image 132
Saeb Amini Avatar answered Sep 27 '22 18:09

Saeb Amini