Last active
December 31, 2015 13:49
-
-
Save keesey/7995398 to your computer and use it in GitHub Desktop.
This file contains 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
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