Add a ToJson()
method to the type:
public class MyClass
{
public string Name {get; set;}
public List<string> Products {get; set;}
public string ToJson()
{
var result = new StringBuilder("{");
result.Append("\"Name\":\"")
.Append(Name)
.Append("\",{\"Products\":[{\"Product\":\"");
var delimiter = "";
foreach(var product in Products)
{
result.Append(delimter).Append(product);
delimiter = "\"},{\"Product\":\"";
}
result.Append("\"}]}");
return result.ToString();
}
}
Then the code becomes:
string str = user.ToJson();
If you need to do this for a number of different types, create an interface they can implement:
interface ICanHazJson
{
string ToJson();
}
And then make each of the types you care about implement the interface:
public class MyClass : ICanHazJson
{
public string Name {get; set;}
public List<string> Products {get; set;}
public string ToJson()
{
var result = new StringBuilder("{");
result.Append("\"Name\":\"")
.Append(Name)
.Append("\",{\"Products\":[{\"Product\":\"");
var delimiter = "";
foreach(var product in Products)
{
result.Append(delimter).Append(product);
delimiter = "\"},{\"Product\":\"";
}
result.Append("\"}]}");
return result.ToString();
}
}
And if there are many types where this matters, that's all the more reason to find a battle-tested json serializer on NuGet that will do what you need and not blow up on some unexpected edge case.