Skip to content

Instantly share code, notes, and snippets.

@tuyen-vuduc
Created January 2, 2017 09:08
Show Gist options
  • Save tuyen-vuduc/d2e0e731548bfeecc2b7cbc6ae59d4b7 to your computer and use it in GitHub Desktop.
Save tuyen-vuduc/d2e0e731548bfeecc2b7cbc6ae59d4b7 to your computer and use it in GitHub Desktop.
JSON to CSharp Generator
function generateClass(className, obj) {
var classes = [];
var buffer = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var val = obj[p],
type = typeof(val),
name = snakeToPascal(p),
cstype = 'object';
if (type == 'object' && val != null) {
if (val instanceof(Date)) {
cstype = 'DateTime';
} else {
classes.push(generateClass(name, val));
cstype = name;
}
} else if (type == 'boolean') {
cstype = 'bool';
} else if (type == 'string') {
cstype = 'string';
//2014-02-21T16:37:12Z
if (/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/.test(val)) {
cstype = 'DateTime';
}
} else if (type == 'number') {
cstype = 'long';
}
buffer.push('\t/* ' + JSON.stringify(val) + ' */');
buffer.push('\tpublic ' + cstype + ' ' + name + ' { get; set; }');
}
}
classes.push('public class ' + className + '\n{\n' +buffer.join('\n') + '\n}');
return classes.join('\n\n');
}
function snakeToPascal(snake) {
return snake.replace(/(^.)|_(.)/img, function(match, g1, g2) {
return (g1 || g2).toUpperCase()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment