5

When trying to update the class properties using JsonConvert.PopulateObject the JsonPathConverter is not called and therefore populate is not done.

Sample class:

[JsonConverter(typeof(JsonPathConverter))]
public class SampleClass
{
    int id;
    [JsonProperty("sample.id")]
    public int Id
    {
        get
        {
            return id;
        }
        set
        {
            id = value;
        }
    }
}

Call to PopulateObject:

var sampleClass = new SampleClass() {
    Id  = 1
};

var str = "{sample:{id:2}}";
JsonConvert.PopulateObject(str, sampleClass, new JsonSerializerSettings());

But the Id property never gets set to 2.

I've tried JsonSerializerSettings with converter = new JsonPathConverter() but it does not work either.

Any idea why it isn't working?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
VeYroN
  • 760
  • 9
  • 19

1 Answers1

0

Note: I am assuming the JsonPathConverter you are referring to in your question is the one in this answer.

ReadJson is only called on a JsonConverter when it is time to instantiate an object which is handled by the converter. Since PopulateObject works on objects that are already instantiated, your converter's ReadJson method will not be called by PopulateObject. This is by design. If you use JsonConvert.DeserializeObject<T> instead of JsonConvert.PopulateObject, then the converter will be called as expected:

var sampleClass = JsonConvert.DeserializeObject<SampleClass>(str);

Fiddle: https://dotnetfiddle.net/lxiirm

Community
  • 1
  • 1
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • Yes, I noticed that it was only called when using DeserializeObject. But i really need to use populate (to update the properties of an existing object). Any idea on how to do that? I can use reflection to copy the values from one object to another, i'm just not sure if using populate would be faster or not... – VeYroN Nov 29 '16 at 07:50
  • Are there any update for this question. In Json.Net 13.0.1, ReadJson was pass existingValue parameter, is is use for Populate – ChauGiang Jan 10 '22 at 14:22
  • Running into this problem in 2023, is there still no solution? I also need to use Populate, as I need control over how my object is constructed but still want to use all the out-of-the-box attribute functionality of Json.Net. Why should it be this way? Why doesn't Populate account for [JsonConverter]? Why does this library still provide no way of invoking baseline deserialisation behaviour? – Thomas Slade Mar 10 '23 at 10:18