Skip to content

Instantly share code, notes, and snippets.

@keesey
Last active December 31, 2015 13: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 keesey/7995398 to your computer and use it in GitHub Desktop.
Save keesey/7995398 to your computer and use it in GitHub Desktop.
module Newtonsoft.Json
{
export function deserialize(o: any): any
{
const dict: { [$id: string]: Object } = {};
function _deserialize(o: any): any
{
if (typeof o === "object" && o !== null)
{
let $id: string;
if ($id = o.$ref)
{
const existing = dict[$id];
if (existing === undefined)
{
throw new Error('Unrecognized $ref ("' + $id + '").');
}
return existing;
}
if ($id = o.$id)
{
dict[$id] = o;
delete o['$id'];
}
for (let prop in o)
{
o[prop] = _deserialize(o[prop]);
}
}
return o;
}
return _deserialize(o);
}
export function serialize(o: any): any
{
const toClean: any[] = [];
let $id = 1;
function _serialize(o: any): any
{
if (typeof o === "object" && o !== null)
{
if (o.hasOwnProperty('$id'))
{
let $ref = o['$id'];
if ($ref === null)
{
$ref = o['$id'] = $id++;
}
return { $ref: $ref };
}
o['$id'] = null;
toClean.push(o);
for (let prop in o)
{
if (o.hasOwnProperty(prop))
{
o[prop] = _serialize(o[prop]);
}
}
}
return o;
}
o = _serialize(o);
const n = toClean.length;
for (let i = 0; i < n; ++i)
{
const objToClean = toClean[i];
if (objToClean['$id'] === null)
{
delete objToClean['$id'];
}
}
return o;
}
}
const serialized = [
{
"$id": 1,
"Name": "James",
"BirthDate": "1983-03-08T00:00Z",
"LastModified": "2012-03-21T05:40Z"
},
{
"$ref": 1
}
];
let deserialized: any;
console.log(JSON.stringify(deserialized = Newtonsoft.Json.deserialize(serialized)));
console.log(JSON.stringify(Newtonsoft.Json.serialize(deserialized)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment