Last active
November 25, 2021 03:52
-
-
Save daiplusplus/1c4a480d902503e7c8888028609bba08 to your computer and use it in GitHub Desktop.
private JsonConstructor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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