Skip to main content
1 of 6
Artur INTECH
  • 7.6k
  • 3
  • 49
  • 41

Another solution where an object is self-sufficient and doesn't expose all possible fields:

A passing test:

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 string Name; public User(string name) { this.Name = name; } public string ToJson() { Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("Name", Name); return JsonSerializer.Serialize(data); } } } 
Artur INTECH
  • 7.6k
  • 3
  • 49
  • 41