10

Suppose I have the following class -

public class A 
{        
   public int P1 { get; internal set; }
}

Using json.net, I am able to serialize the type with P1 property. However, during deserialization, P1 is not set. Without modifying class A, is there an in build way to handle this? In my case, I am using a class from a different assembly and cannot modify it.

ambivi
  • 235
  • 1
  • 3
  • 9
  • Does this answer your question? [Private setters in Json.Net](https://stackoverflow.com/questions/4066947/private-setters-in-json-net) – StayOnTarget Jul 22 '20 at 20:43

3 Answers3

10

Yes, you can use a custom ContractResolver to make the internal property writable to Json.Net. Here is the code you would need:

class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);

        if (member.DeclaringType == typeof(A) && prop.PropertyName == "P1")
        {
            prop.Writable = true;
        }

        return prop;
    }
}

To use the resolver, create an instance of JsonSerializerSettings and set its ContractResolver property to a new instance of the custom resolver. Then, pass the settings to JsonConvert.DeserializeObject<T>().

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"{ ""P1"" : ""42"" }";

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.ContractResolver = new CustomResolver();

        A a = JsonConvert.DeserializeObject<A>(json, settings);

        Console.WriteLine(a.P1);
    }
}

Output:

42

Fiddle: https://dotnetfiddle.net/1fw2lC

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • 1
    BrianRogers followed your example but removed the condition to check type and property as wanted all to be writable. It worked. Thanks :) – Ricardo stands with Ukraine Sep 26 '16 at 15:49
  • I stumbled on this answer while looking for `string prop {get;}`. This answer does not work for this use-case, throwing a `NullReferenceException` somewhere during deserialization. The difference is the missing `internal set;` – Timo Jun 29 '22 at 20:01
4

After some experimenting, I've found that a property is deserialised correctly if you decorate your property with:

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)] 

Applying to the class in the original question:

public class A 
{
   [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]        
   public int P1 { get; internal set; }
}
Andy Dobedoe
  • 707
  • 1
  • 7
  • 9
  • 1
    Be careful with this, according to the documentation this should have *no effect* when deserializing. https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm – Stewart Ritchie Dec 04 '18 at 09:53
  • 7
    Actually, it has nothing to do with DefaultValueHandling, you could decorate it with just [JsonProperty] and get same effect. – irriss Apr 01 '19 at 02:25
2

This is my solution to handle in more general case:

class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty result = base.CreateProperty(member, memberSerialization);

        var propInfo = member as PropertyInfo;
        result.Writable |= propInfo != null 
             && propInfo.CanWrite
             && !propInfo.IsPrivate;

        return result;
    }
}

With class CInternalSetter:

class CInternalSetter
{
    public CInternalSetter()
    {
        LoggedEmployeeId3 = 10;
    }
    public int LoggedEmployeeId { get; set; }
    public int LoggedEmployeeId2 { get; internal set; }
    public int LoggedEmployeeId3 { get; }
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this, Formatting.Indented);
    }
}

Then test it with against this class:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CustomResolver();

var c = new CInternalSetter()
{
    LoggedEmployeeId = 1,
    LoggedEmployeeId2 = 2
};

var cString = JsonConvert.SerializeObject(c);

Console.WriteLine(cString);
Console.WriteLine(JsonConvert.DeserializeObject<CInternalSetter>(cString).ToString());
Console.WriteLine("-------------------------------------------");
Console.WriteLine(JsonConvert.DeserializeObject<CInternalSetter>(cString, settings).ToString());
Gerke Geurts
  • 632
  • 4
  • 9
hakuna1811
  • 524
  • 5
  • 11
  • 1
    This general implementation was exactly what I needed, but I think there's a typo in the CreatePropertyMethod: `propInfo.IsPrivate` should be `propInfo.SetMethod.IsPrivate` – The Mad Coder May 16 '18 at 18:25