2

I'm using the Newtosoft Json.NET library for deserializing API responses to objects. But I need to update already deserialized object with a partial update (e.g. JSON containig with only changed properties).

For example:

I have a person model (of course simplified):

public class PersonModel
{    
  public string Name { get; set; }
  public string Surname{ get; set; }
  public int Age { get; set; }
}

and a instance of Person deserialized from JSON data:

{  
   "name": "John",
   "surname": "Newton",
   "age": 20
}

Then I get JSON with changes:

{  
   "age": 21
}

and I need to update my instannce with this JSON (so only age property of my instance will be updated to value 21)

Is there a simple way how to do it?

user990423
  • 1,397
  • 2
  • 12
  • 32
Dominik Palo
  • 2,873
  • 4
  • 29
  • 52

1 Answers1

-2

According to this question: How to update a property of a JSON object using NewtonSoft

You can access the object by using properties as keys:

string jsonInstance = "{  
   "name": "John",
   "surname": "Newton",
   "age": 20
}";

string jsonEdit = "{  
   "age": 21
}";

JObject instance = JObject.Parse(jsonInstance);
JObject edit = JObject.Parse(jsonEdit);
instance["age"] = edit["age"];
Community
  • 1
  • 1
Phate01
  • 2,499
  • 2
  • 30
  • 55
  • 3
    Yes but how will code know which properties are returned in partial JSON update.!? – Nikhil Vartak Nov 25 '15 at 16:25
  • 3
    My question still remains the same. Partial update JSON may return surname and age both. How would code understand that it has to update these 2 specific properties in original person object. – Nikhil Vartak Nov 25 '15 at 16:26
  • If he's getting jsoned edits to be made, simply parse it into a JObject, as explained in my code – Phate01 Nov 25 '15 at 16:27
  • 2
    But how does he know that it's the age property that's changing and not, say, the surname property. You need some way of inspecting the JSON before using the values to update the instance. – James Thorpe Nov 25 '15 at 16:28
  • I assume he's getting the same object with changes, so I'd change all properties if not null. Anyway some tests are required for this, when I have some time I'm gonna do them – Phate01 Nov 25 '15 at 16:33