In my recommended approach, I propose the following implementation with explanatory comments. It is important to note that there may be errors in the code as it has not been verified, therefore additional refinement may be required.
Main Concept: Simplify the code within your components by encapsulating your array into an object named JsonDevices. Subsequently, you can create a custom converter to handle the conversion process seamlessly.
Key Classes
// Custom serialization/deserialization logic.
// Implementation of serialize and deserialize methods is mandatory.
@JsonConverter
class DeviceConverter implements JsonCustomConvert<Device> {
// Serialization of the instance using json2typescript standard method.
serialize(device: Device): any {
const jsonConvert: JsonConvert = new JsonConvert();
return jsonConvert.serialize(device);
}
// Upon receiving a JSON object (not string), determine whether to instantiate Computer or Mobile based on provided properties.
deserialize(device: any): Device {
const jsonConvert: JsonConvert = new JsonConvert();
// Try/catch block used due to potential errors in deserialization
try {
if (device.name && device.macAddress) {
const computer: Computer = new Computer();
computer.name = device.name;
computer.macAddres = device.macAddress;
return jsonConvert.deserialize(computer, Computer);
} else if (device.name && device.number) {
const mobile: Mobile = new Mobile();
mobile.name = device.name;
mobile.number = device.number;
return jsonConvert.deserialize(mobile, Mobile);
}
} catch(e) {}
throw new TypeError();
}
}
@JsonObject
class JsonDevices {
@JsonProperty("devices", DeviceConverter)
devices: Device[] = [];
}
@JsonObject
class Device {
@JsonProperty("name", String)
name: string = undefined;
}
@JsonObject
class Mobile extends Device {
@JsonProperty("number", String)
number: string = undefined;
}
@JsonObject
class Computer extends Device {
@JsonProperty("macAddress", String)
macAddress: string = undefined;
}
Utilization
// Sample incoming JSON data
const jsonString: string = ("
[{
'name':'mobile1',
'number':'600 600 600',
'class':'Mobile'
},{
'name':'computer',
'macAddress:'123123123',
'class':'Computer'
}]
");
// Convert JSON string to JavaScript object
const jsonArray: any[] = JSON.parse(jsonString);
// Group the array under an object containing a device array
const jsonDevicesObject: any = {
devices: jsonArray;
}
// Perform deserialization using json2typescript:
const jsonConvert: JsonConvert = new JsonConvert();
const jsonDevices: JsonDevices = jsonConvert.deserialize(jsonDevicesObject, JsonDevices);
// Each element within jsonDevices.devices will now represent either a Mobile or Computer instance