Skip to content

Instantly share code, notes, and snippets.

@jessegavin
Created August 18, 2011 02:31
Show Gist options
  • Save jessegavin/1153155 to your computer and use it in GitHub Desktop.
Save jessegavin/1153155 to your computer and use it in GitHub Desktop.
Code example for StackOverflow question #7087312
// ----------------------------------------------------------------
// This example shows my solution for the question I posted here:
// http://stackoverflow.com/questions/7087312
// ----------------------------------------------------------------
public class Person {
public string First { get; set; }
public string Last { get; set; }
public string Twitter { get; set; }
}
public class GridData {
public string[] Columns { get; set; }
public object[] Rows { get; set; }
}
void Main()
{
var list = new List<Person> {
new Person { First = "Jesse", Last = "Gavin", Twitter = "jessegavin" },
new Person { First = "John", Last = "Sheehan", Twitter = "johnsheehan" }
};
var data = new GridData {
Columns = list.First().GetType()
.GetProperties()
.Select(pi => pi.Name).ToArray(),
Rows = (from x in list
select x.GetType()
.GetProperties()
.Where (y => y.GetGetMethod() != null)
.Select(prop => prop.GetValue(x, null)).ToArray()).ToArray()
};
var json = JsonConvert.SerializeObject(data).Dump();
/*
--------------------------------------------------
'json' is a string containing the following:
{
"Columns" : ["First","Last","Twitter"],
"Rows" : [
["Jesse","Gavin","jessegavin"],
["John","Sheehan","johnsheehan"]
]
}
--------------------------------------------------
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment