Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Foo
- {
- public int Prop1;
- [DefaultValue("")]
- public string Prop2;
- public int? Prop3;
- public Bar Prop4;
- public Bar[] Prop5;
- };
- public class Bar
- {
- public int Prop1;
- public string Prop2;
- public int? Prop3;
- };
- public void NullOrEmptyStringTerminator()
- {
- var bar = new Bar { Prop1 = 0, Prop2 = "", Prop3 = 0 };
- var bar2 = new Bar { Prop1 = 0, Prop3 = 0 };
- var inputs = new[] {
- new Foo{ Prop1= 1, Prop2="", Prop4= bar, Prop5 = new []{bar,bar,bar} },
- new Foo{ Prop1= 1, Prop4= bar, Prop5 = new []{bar2,bar2,bar2} },
- };
- var jsonResults =
- inputs
- .Select(x =>
- new
- {
- Item = x,
- NormalSerialisation =
- JsonConvert.SerializeObject(
- x,
- Formatting.Indented,
- new JsonSerializerSettings { }
- ),
- CustomSerialisation =
- JsonConvert.SerializeObject(
- x,
- Formatting.Indented,
- new JsonSerializerSettings
- {
- NullValueHandling = NullValueHandling.Ignore,
- DefaultValueHandling = DefaultValueHandling.Ignore,
- })
- }
- ).ToList();
- }
- using System;
- using System.Linq;
- using System.Collections.Generic;
- using System.ComponentModel;
- using Newtonsoft.Json;
- public class Program
- {
- public static void Main()
- {
- var inputs = new List<object>()
- {new Foo{Prop2 = "" , Bar = new Bar()}};
- foreach (object input in inputs)
- {
- string NormalSerialisation = JsonConvert.SerializeObject(input, Formatting.Indented, new JsonSerializerSettings{});
- string CustomSerialisation = JsonConvert.SerializeObject(input, Formatting.Indented, new JsonSerializerSettings{NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore});
- Console.WriteLine("normal:");
- Console.WriteLine(NormalSerialisation);
- Console.WriteLine("custom:");
- Console.WriteLine(CustomSerialisation);
- }
- }
- public class Foo
- {
- public string Prop2
- {
- get;
- set;
- }
- public Bar Bar
- {
- get;
- set;
- }
- }
- public class Bar
- {
- [DefaultValue("")]
- public string Prop2;
- }
- }
- normal:
- {
- "Prop2": "",
- "Bar": {
- "Prop2": null
- }
- }
- custom:
- {
- "Prop2": "",
- "Bar": {}
- }
Add Comment
Please, Sign In to add comment