How can I create a JsonPatchDocument from comparing two c# objects?

asked9 years ago
last updated8 years ago
viewed15.6k times
Up Vote29Down Vote

Given I have two c# objects of the same type, I want to compare them to create a JsonPatchDocument.

I have a StyleDetail class defined like this:

public class StyleDetail
    {
        public string Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public decimal OriginalPrice { get; set; }
        public decimal Price { get; set; }
        public string Notes { get; set; }
        public string ImageUrl { get; set; }
        public bool Wishlist { get; set; }
        public List<string> Attributes { get; set; }
        public ColourList Colours { get; set; }
        public SizeList Sizes { get; set; }
        public ResultPage<Style> Related { get; set; }
        public ResultPage<Style> Similar { get; set; }
        public List<Promotion> Promotions { get; set; }
        public int StoreStock { get; set; }
        public StyleDetail()
        {
            Attributes = new List<string>();
            Colours = new ColourList();
            Sizes = new SizeList();
            Promotions = new List<Promotion>();
        }
    }

if I have two StyleDetail objects

StyleDetail styleNew = db.GetStyle(123);
StyleDetail styleOld = db.GetStyle(456);

I now want to create a JsonPatchDocument so I can send the differences to my REST API... How to do this??

JsonPatchDocument patch = new JsonPatchDocument();
// Now I want to populate patch with the differences between styleNew and styleOld - how?

in javascript, there is a library to do this https://www.npmjs.com/package/rfc6902

Calculate diff between two objects:rfc6902.createPatch({first: 'Chris'}, {first: 'Chris', last: 'Brown'});``` [ { op: 'add', path: '/last', value: 'Brown' } ]



but I am looking for a c# implementation