4

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
  • 118,414
  • 30
  • 277
  • 278
VeYroN
  • 690
  • 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
  • 118,414
  • 30
  • 277
  • 278
  • 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