Skip to content

Instantly share code, notes, and snippets.

@pcuenca
Created September 5, 2023 18:27
Show Gist options
  • Save pcuenca/968f3367b4cd419045b2f3e53bb28626 to your computer and use it in GitHub Desktop.
Save pcuenca/968f3367b4cd419045b2f3e53bb28626 to your computer and use it in GitHub Desktop.
dotnet dynamic property wrapper
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Text.RegularExpressions;
public class CamelToSnakeDynamicWrapper : DynamicObject
{
private readonly JObject _jObject;
public static string CamelToSnake(string camelCase)
{
if (string.IsNullOrEmpty(camelCase))
{
return camelCase;
}
string snakeCase = Regex.Replace(camelCase, "(?<!^)([A-Z])", "_$1");
return snakeCase.ToLowerInvariant();
}
public CamelToSnakeDynamicWrapper(JObject jObject)
{
_jObject = jObject;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
// Try to get the property value with a case-insensitive search
JToken jToken = _jObject.GetValue(binder.Name, StringComparison.OrdinalIgnoreCase);
if (jToken != null)
{
result = jToken.ToObject<object>();
return true;
}
// Convert to snake case and try again
string snakeCase = CamelToSnake(binder.Name);
jToken = _jObject.GetValue(snakeCase, StringComparison.OrdinalIgnoreCase);
if (jToken != null)
{
result = jToken.ToObject<object>();
return true;
}
result = null;
return false;
}
}
public class Program
{
public static void Main()
{
string jsonString = "{\"tokenizer_class\":\"LlamaTokenizer\", \"add_bos_token\":true}";
// Parse the JSON string to a JObject
JObject parsedObject = JObject.Parse(jsonString);
// Wrap the parsed object with our dynamic case-insensitive wrapper
dynamic wrappedObject = new CamelToSnakeDynamicWrapper(parsedObject);
Console.WriteLine(wrappedObject.tokenizer_class);
Console.WriteLine(wrappedObject.tokenizerClass);
Console.WriteLine(wrappedObject.addBosToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment