Disclaimer: this code is not optimized in any way. I am absolutely open to suggestion of any kind. As a matter of fact, I am keen on learning the best way to work with semantic data, but so far I have not found solid code which will help convince my colleagues.
This code is an adaptation of the code in this blogpost. It basically converts a Json object into an dynamic object which can then be easily queried. Since Freebase returns Json I found this extension method very helpful. You will need the Json.Net library which can be downloaded from codeplex.
public static class JTokenExtensions
{
public static object ToDynamicObject(this JToken token)
{
if (token is JValue)
{
return ((JValue)token).Value;
}
if (token is JObject)
{
var expando = new ExpandoObject();
var query = from childToken in (token)
where childToken is JProperty
select childToken as JProperty;
foreach (var property in query.ToList())
{
var propertyName = string.Format("{0}{1}", char.ToUpper(property.Name[0]), property.Name.Substring(1));
((IDictionary<string, object>)expando).Add(propertyName, property.Value.ToDynamicObject());
}
return expando;
}
if ((token is JArray))
{
return token.Select(t => t.ToDynamicObject()).ToList();
}
throw new ArgumentException(string.Format("Unknown token type '{0}'", token.GetType()), "token");
}
}
Example usage:
var json = SomeMethodThatGetsJsonFromFreebase();
var jsonObject = JObject.Parse(json);
dynamic response = jsonObject.ToDynamicObject();
var query = from a in (response.A0.Result.Album as List<dynamic>)
where a.Name.ToUpperInvariant().StartsWith("A")
select a;
foreach (var album in query)
{
Console.Out.WriteLine(album.Name);
}