Advertisement
teleias

JsonDifferenceDetector

Jun 24th, 2022
1,175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using System.Text.Json;
  6.  
  7. var p = new JsonDifferenceDetector();
  8. JsonDifferenceDetector.Main(new string[]{});
  9. public class JsonDifferenceDetector
  10. {
  11.     public static void Main(string[] args)
  12.     {
  13.         var x = new Example(){a = 1, b = "2", c = DateTime.Now};
  14.         var y = new Example(){a = 1, b = "two", c = DateTime.Now.AddDays(1)};
  15.            
  16.         Compare(x, y);
  17.     }
  18.        
  19.     public static void Compare(Example x, Example y)
  20.     {
  21.         var jso = new JsonSerializerOptions(){WriteIndented = true};
  22.         string xs = JsonSerializer.Serialize(x, jso);
  23.         string ys = JsonSerializer.Serialize(y, jso);
  24.        
  25.         // Console.WriteLine(xs);
  26.         // Console.WriteLine(ys);
  27.  
  28.         Regex keyValue = new Regex("\"(?<key>\\w+)\": (?<val>.+)(,|)$");
  29.         string[] xArr = xs.Split("\n");
  30.         string[] yArr = ys.Split("\n");
  31.         for (int i = 0; i < xArr.Length; i++)
  32.         {
  33.             var xLine = xArr[i];
  34.             var yLine = yArr[i];
  35.             if (xLine == yLine)
  36.             {
  37.                 continue;
  38.             }
  39.  
  40.             Match xm = keyValue.Match(xLine);
  41.             Match ym = keyValue.Match(yLine);
  42.  
  43.             string key = xm.Groups["key"].Value;
  44.             string xv = xm.Groups["val"].Value;
  45.             string yv = ym.Groups["val"].Value;
  46.            
  47.             Console.WriteLine($"{key}: {xv} -> {yv}");
  48.         }
  49.     }
  50. }
  51. [Serializable]
  52. public class Example
  53. {
  54.     public int a { get; set; }
  55.     public string b { get; set; }
  56.     public DateTime c { get; set; }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement