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);
2
  • 2
    You want JsonConvert.PopulateObject(). See here for a similar question. Commented Jun 1, 2017 at 7:05
  • that works fine thank you,that question not come in my serach... Commented Jun 1, 2017 at 7:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.