Skip to content

Instantly share code, notes, and snippets.

@jesslilly
Created June 25, 2014 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesslilly/891282f7149247a9fffa to your computer and use it in GitHub Desktop.
Save jesslilly/891282f7149247a9fffa to your computer and use it in GitHub Desktop.
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