Skip to content

Instantly share code, notes, and snippets.

@daiplusplus
Last active November 25, 2021 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daiplusplus/1c4a480d902503e7c8888028609bba08 to your computer and use it in GitHub Desktop.
Save daiplusplus/1c4a480d902503e7c8888028609bba08 to your computer and use it in GitHub Desktop.
private JsonConstructor example
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
void Main()
{
HasPrivateCtor e = new HasPrivateCtor( "123" );
String js = JsonConvert.SerializeObject( e );
HasPrivateCtor e2 = JsonConvert.DeserializeObject<HasPrivateCtor>( js )!;
Boolean ok = ( e.A == e2.A && e.B == e2.B );
if( !ok ) throw new InvalidOperationException();
}
public class HasPrivateCtor
{
public HasPrivateCtor( String text )
{
this.A = text;
this.B = text.Length;
}
[JsonConstructor]
private HasPrivateCtor( [JsonProperty("a")] String a, [JsonProperty("b")] Int32 b )
{
this.A = a;
this.B = b;
}
[JsonProperty("a")]
public String A { get; }
[JsonProperty("b")]
public Int32 B { get; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment