Skip to content

Instantly share code, notes, and snippets.

@praschl
Last active May 24, 2018 17:26
Show Gist options
  • Select an option

  • Save praschl/d0defaf51c8456ab9978e465cc45c40b to your computer and use it in GitHub Desktop.

Select an option

Save praschl/d0defaf51c8456ab9978e465cc45c40b to your computer and use it in GitHub Desktop.
Format JObject as HTML
public class HtmlFormatter
{
#region Public Methods
public void Format(JObject item, TextWriter writer)
{
writer.WriteLine("<table>");
foreach (JProperty property in item.Properties())
{
writer.WriteLine("<tr>");
writer.WriteLine(Invariant($"<td>{property.Name}</td>"));
writer.WriteLine("<td>");
if (property.Value is JValue value)
{
if (!value.HasValues)
{
writer.WriteLine("<i>null</i>");
}
else
{
writer.WriteLine(value);
}
}
if (property.Value is JObject obj)
Format(obj, writer);
if (property.Value is JArray array)
Format(array, writer);
writer.WriteLine("</td>");
writer.WriteLine("</tr>");
}
writer.WriteLine("</table>");
}
public void Format(JArray array, TextWriter writer)
{
// get all column names by searching all objects in array for properties, and give each propertyname a column number.
// write out column names
// write out objects
}
#endregion
}
[TestClass]
public class UnitTest1
{
#region Public Methods
[TestMethod]
public void TestMethod1()
{
HtmlFormatter f = new HtmlFormatter();
Person p = new Person
{
Name = "Michael",
Id = 13,
Birth = DateTime.Now,
Child = new Child { Id = 29, Name = "Simon"}
};
JObject obj = JObject.FromObject(p);
using (StringWriter writer = new StringWriter())
{
f.Format(obj, writer);
Console.WriteLine(writer.ToString());
}
}
#endregion
}
public class Person
{
#region Public Properties
public string Name
{
get;
set;
}
public int Id
{
get;
set;
}
public DateTime Birth
{
get;
set;
}
public Child Child
{
get;
set;
}
public string Null
{
get;
set;
}
#endregion
}
public class Child
{
public string Name;
public int Id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment