-
Notifications
You must be signed in to change notification settings - Fork 1
fromJson
Brad Sickles edited this page Nov 27, 2015
·
7 revisions
interface Function {
fromJson<T>(o: any, mappingOverrides?: any): T;
}
This can be used to easily project a class definition on a raw json object. Subproperties can also be mapped using a static $jsonMappings
member on the parent class. These mappings can be overriden using the optional mappingOverrides
json input.
The following example illustrates usage. Note that you can also map arrays of subproperties by placing the projection function inside an Array as the first and only element.
class Batch {
static $jsonMappings = {
'owner': x => Person.fromJson(x),
'entries': [x => Entry.fromJson(x)]
};
owner: Person = null;
entries: Entry[] = [];
}
class Person {
name: string;
}
class Entry {
id: number;
}
var json = [
{
owner: {
name: 'John Doe'
},
entries: [
{ id: 1 },
{ id: 2 }
]
},
{
owner: {
name: 'Jane Doe'
},
entries: []
}
];
var batches = json.en().select(batch => Batch.fromJson(batch)).toArray();
// batches results in Batch[] with data filled in from json.
exjs is intended to automate mapping structured data. By default, every member on the input object will be mapped onto the output object.
The following list describes the mode of operations. Each progressive step will ignore members that have already been mapped.
- Run through each member in
mappingOverrides
. - Run through each member in
$jsonMappings
static member. - Run through the remaining keys in the input object.