1

I want to deserialize a json string to my object without create new instance of my object because I loaded my object when my app is started and I just want update properties of my class and dont want to create new instance when I using json deserialization.

Fo example normal json deserialer work fine in this example and this create new instance of object:

var obj = JsonConvert.DeserializeObject<MyData>("json string to deserialize");

In my case I have an instance of my object and I want to deserialize and map properties to my object:

    MyData data = new MyData() { Age = 27, Name = "Ali" };
    //this is my case what I want:
    JsonConvert.DeserializeObject("json string to deserialize and mapp", ref data);
    //or:
    JsonConvert.DeserializeObject("json string to deserialize and mapp", data);
Ali Yousefi
  • 2,355
  • 2
  • 32
  • 47
  • 2
    You want [`JsonConvert.PopulateObject()`](http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_PopulateObject.htm). See [here](https://stackoverflow.com/q/27511675/3744182) for a similar question. – dbc Jun 01 '17 at 07:05
  • that works fine thank you,that question not come in my serach... – Ali Yousefi Jun 01 '17 at 07:10

1 Answers1

1

that was an interesting question. how about this:

    var data = new MyData() { Age = 27, Name = "Ali" };
    var dataType = typeof(MyData);
    var obj = JsonConvert.DeserializeObject<MyData>(richTextBox1.Text);

    var binding = BindingFlags.Instance | BindingFlags.Public;
    var properties = obj.GetType().GetProperties(binding);
    foreach (var property in properties)
    {
        if (!property.CanRead)
            continue;

        var value = property.GetValue(obj);

        if (ReferenceEquals(value, null))
            continue;

        dataType.GetProperty(property.Name).SetValue(data, value);
    }

Note: JsonConvert.PopulateObject() overwrite exiting properties. in my solution exiting properties doesn't overwrite.

Mohammad
  • 2,724
  • 6
  • 29
  • 55