Program.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using Newtonsoft.Json.Serialization;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text.RegularExpressions;
  10. namespace D12._2
  11. {
  12. public class PropertyIgnoreSerializerContractResolver : DefaultContractResolver
  13. {
  14. protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  15. {
  16. var property = base.CreateProperty(member, memberSerialization);
  17. if (property.PropertyName == "red")
  18. {
  19. property.ShouldSerialize = i => false;
  20. property.Ignored = true;
  21. }
  22. return property;
  23. }
  24. }
  25. class Program
  26. {
  27. static void Main(string[] args)
  28. {
  29. if (args.Length < 1) throw new ArgumentException();
  30. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  31. var input = File.ReadAllText(args[0]);
  32. // Use dynamic to skip the use of specialized functions and a factory pattern
  33. dynamic n = JsonConvert.DeserializeObject(input);
  34. var result = SumValues(n);
  35. Console.WriteLine($"The answer is : {result}");
  36. }
  37. private static long SumValues(JValue n) => n.Type == JTokenType.Integer ? (long) n.Value : 0;
  38. private static long SumValues(JObject n)
  39. {
  40. if (n.Properties().Any(p => (p.Value as JValue)?.Value as string == "red"))
  41. return 0;
  42. return n.Properties().Sum((dynamic a) => (long)SumValues(a.Value));
  43. }
  44. private static long SumValues(JArray n) => n.Sum((dynamic a) => (long)SumValues(a));
  45. }
  46. }