JSON Serializer Object with Internal Properties

I have a class with some internal properties, and I would like to also serialize them in json. How can i do this? for instance

public class Foo { internal int num1 { get; set; } internal double num2 { get; set; } public string Description { get; set; } public override string ToString() { if (!string.IsNullOrEmpty(Description)) return Description; return base.ToString(); } } 

Saving with

 Foo f = new Foo(); f.Description = "Foo Example"; JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; string jsonOutput = JsonConvert.SerializeObject(f, Formatting.Indented, settings); using (StreamWriter sw = new StreamWriter("json_file.json")) { sw.WriteLine(jsonOutput); } 

I get

 { "$type": "SideSlopeTest.Foo, SideSlopeTest", "Description": "Foo Example" } 
+6
source share
1 answer

Mark the internal properties with the [JsonProperty()] attribute:

 public class Foo { [JsonProperty()] internal int num1 { get; set; } [JsonProperty()] internal double num2 { get; set; } public string Description { get; set; } public override string ToString() { if (!string.IsNullOrEmpty(Description)) return Description; return base.ToString(); } } 

And then, to check:

  Foo f = new Foo(); f.Description = "Foo Example"; f.num1 = 101; f.num2 = 202; JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; var jsonOutput = JsonConvert.SerializeObject(f, Formatting.Indented, settings); Debug.WriteLine(jsonOutput); 

I get the following output:

 { "$type": "Tile.JsonInternalPropertySerialization.Foo, Tile", "num1": 101, "num2": 202.0, "Description": "Foo Example" } 

(where "Tile.JsonInternalPropertySerialization" and "Tile" are the namespace names and assembly names that I use).

+13
source

Source: https://habr.com/ru/post/978047/


All Articles