I wanted to share this code in case anyone might find it helpful, but I also wanted any thoughts on the efficiency or the wisdom of doing this operation. I have to admit that I'm very new to using LINQ, so I'm unsure what the performance implications are for the "ToDictionary" operation, or doing it recursively for that matter.
- Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using PlayerIO.GameLibrary;
using MiniJSON;
public static class DatabaseObjectExtensions
{
public static string ToSerializedJson(this DatabaseObject dbObj)
{
Dictionary<string, object> dict = dbObj.ToDictionary(KeySelector, ValueSelector);
return Json.Serialize(dict);
}
private static string KeySelector(KeyValuePair<string, object> entry)
{
return entry.Key;
}
private static object ValueSelector(KeyValuePair<string, object> entry)
{
if(entry.Value is DatabaseObject)
{
DatabaseObject temp = (DatabaseObject)entry.Value;
return temp.ToDictionary(KeySelector, ValueSelector);
}
else
{
return entry.Value;
}
}
}
The only external dependency for this code is MiniJSON, which is a single .cs file with JSON serialize and deserialize functionality. Maybe you can use C#'s built-in JSON parsers, but I think MiniJSON is a bit faster.
Anyway, if anyone has any comments or criticisms, please let me know. My main concern is that I am somehow doing something horribly inefficient by transferring DatabaseObjects in this way.
Thanks!