Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
JSON to C# POCO converter. I started working on this and then stopped. Saving the code in case I need it later.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Web.Helpers;
namespace Custom.Utils
{
class CustomJson
{
public static void Parse(Object model, string json)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
// Parse JSON into a dynamic.
dynamic obj = Json.Decode(json);
// Also cast the dynamic into a dictionary so we can enumerate the keys.
var dict = (Dictionary<string, object>)obj;
foreach (string key in dict.Keys)
{
// Camelcase the key.
var camelKey = textInfo.ToTitleCase(key);
// See if our model has that property.
var prop = model.GetType().GetProperty(camelKey);
if (prop != null)
{
prop.SetValue(obj["key"]);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment