JSON Serializer object with internal properties

后端 未结 1 1371
灰色年华
灰色年华 2020-11-28 16:26

I have class with some internal properties and I would like to serialize them into json as well. How can I accomplish this? For example

public class Foo
{
          


        
相关标签:
1条回答
  • 2020-11-28 17:03

    Mark the internal properties to be serialized 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 later, to test:

    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);
    
    Console.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 namespace and assembly names I am using).

    As an aside, when using TypeNameHandling, do take note of this caution from the Newtonsoft docs:

    TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than None.

    For a discussion of why this may be necessary, see TypeNameHandling caution in Newtonsoft Json and and External json vulnerable because of Json.Net TypeNameHandling auto?.

    0 讨论(0)
提交回复
热议问题