https://stackoverflow.com/questions/54135005/shouldserialize-with-xml-and-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.Xml.Serialization;
using System.Xml;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

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

//https://stackoverflow.com/questions/54135005/shouldserialize-with-xml-and-json

	public class UnitTest1
	{
		private readonly Customer _customer = new Customer
			{
				FirstName = "Paulo",
				LastName = "Balbino",
				Age = 25
			};

		[Serializable]
		public class Customer
		{
			[XmlElement("FirstName")]
			public string FirstName { get; set; }

			[XmlElement("LastName")]
			public string LastName { get; set; }

			[XmlElement("Age")]
			public int Age { get; set; }

			public bool ShouldSerializeLastName()
			{
				return Age > 30; // Enter here only if it is XmlSerialize.
			}
		}

		public void XmlSerialize()
		{
			var xmlSerializer = new XmlSerializer(typeof(Customer));

			using (var textWriter = new StringWriter())
			{
				xmlSerializer.Serialize(textWriter, _customer);
				var xml = textWriter.ToString();
				Console.WriteLine(xml);
				Assert.IsTrue(!xml.Contains(_customer.LastName));
			}
		}

		static DefaultContractResolver IgnoreShouldSerializeContractResolver = new DefaultContractResolver
		{
			IgnoreShouldSerializeMembers = true,
			//Set other properties as required:
			//NamingStrategy = new CamelCaseNamingStrategy(),
		};
		
		public void JsonConvert()
		{
			var settings = new JsonSerializerSettings
			{
				ContractResolver = IgnoreShouldSerializeContractResolver,
			};
			var json = Newtonsoft.Json.JsonConvert.SerializeObject(_customer, settings);
			Console.WriteLine(json);
			Assert.IsTrue(json.Contains(_customer.LastName));
		}
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				new UnitTest1().XmlSerialize();
				new UnitTest1().JsonConvert();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;