Skip to main content
6 of 6
added 26 characters in body
Artur INTECH
  • 7.6k
  • 3
  • 49
  • 41

October 2023 update:

Another solution using built-in System.Text.Json (.NET Core 3.0+) where an object is self-sufficient and doesn't expose all possible fields:

A passing test (using NUnit):

using NUnit.Framework; namespace Intech.UnitTests { public class UserTests { [Test] public void ConvertsItselfToJson() { var userName = "John"; var user = new User(userName); var actual = user.ToJson(); Assert.AreEqual($"{{\"Name\":\"{userName}\"}}", actual); } } } 

An implementation:

using System.Text.Json; using System.Collections.Generic; namespace Intech { public class User { private readonly string name; public User(string name) { this.name = name; } public string ToJson() { var params = new Dictionary<string, string>{{"Name", name}}; return JsonSerializer.Serialize(params); } } } 
Artur INTECH
  • 7.6k
  • 3
  • 49
  • 41