[Fork] [Fork] https://stackoverflow.com/questions/58997718/modifying-a-json-file-using-system-text-json

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/58997718/modifying-a-json-file-using-system-text-json

    class TestClass
    {
        public static void Test()
        {
			var newJson = TestMethod();
			Console.WriteLine("\nNew users only: ");
			Console.WriteLine(newJson());
		}
		
        public static Func<string> TestMethod()
        {
			ICollection<long> existingUserIds;
			
			using(var existingUsersDocument = JsonDocument.Parse(GetExistingUsersJson()))
			{
				existingUserIds = existingUsersDocument.RootElement.EnumerateArray().Select(u => u.GetProperty("id").GetInt64()).ToHashSet();
			}
			
			Console.Write("\nExisting user ids:");
			Console.WriteLine(JsonSerializer.Serialize(existingUserIds));
			
			Predicate<long> shouldSkip = i => existingUserIds.Contains(i);
			
			var rawJsonDownload = GetRawJsonDownload();
			
			using var usersDocument = JsonDocument.Parse(rawJsonDownload);
			var users = usersDocument.RootElement.EnumerateArray()
				.Where(e => !shouldSkip(e.GetProperty("id").GetInt64()))
				.Select(e => e.Clone())
				.ToList();
			
			return Json(users);
		}	
		
		public static Func<string> Json<T>(T obj)
		{
			return () => JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true });
		}
		
		static string GetRawJsonDownload()
		{
			var json = @"[
   {
      ""id"":3,
      ""name"":""name 3"",
      ""address"" : { ""Line1"" : ""line 1"", ""Line2"" : ""line 2""},
      ""discount"" : 123.1212121121212121
   },
   {
      ""id"":4,
      ""name"":""name 4"",
      ""address"" : { ""Line1"" : ""line 1"", ""Line2"" : ""line 2""},
      ""discount"" : 22.220000000000000000000
   },
   {
      ""id"":5,
      ""name"":""name 5"",
      ""address"" : { ""Line1"" : ""line 1"", ""Line2"" : ""line 2""},
      ""discount"" : 123.1212121121212121
   }
]";
			return json;
		}
		
		static string GetExistingUsersJson()
		{
			var json = @"[
   {
      ""id"":1,
      ""name"":""name 1"",
      ""address"" : { ""Line1"" : ""line 1"", ""Line2"" : ""line 2""},
      ""discount"" : 10.1100000000000000000000000
   },
   {
      ""id"":2,
      ""name"":""name 2"",
      ""address"" : { ""Line1"" : ""line 1"", ""Line2"" : ""line 2""},
      ""discount"" : 123.1212121121212121
   },
   {
      ""id"":3,
      ""name"":""name 3"",
      ""address"" : { ""Line1"" : ""line 1"", ""Line2"" : ""line 2""},
      ""discount"" : 123.1212121121212121
   }
]";
			return json;
		}
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;