Created
June 25, 2014 15:49
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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