[英]Is it possible to handle unknown properties when creating a TS class instance from JSON?
When converting a plain object from JSON to a class instance, I need a way to catch all properties that have no corresponding class properties and store them in a some place (additionalData in the example below).将普通对象从 JSON 转换为类实例时,我需要一种方法来捕获没有相应类属性的所有属性并将它们存储在某个位置(下面示例中的 additionalData)。
I looked into some libraries ( class-transformer , marshal.ts , TypedJSON ) but there seems to be no means to do what I want.我查看了一些库( class-transformer 、 marshal.ts 、 TypedJSON ),但似乎没有办法做我想做的事。
Below is a hypothetical example of what I would like to achieve (it uses class-transformer but any other deserializer library would work for me)下面是我想要实现的假设示例(它使用类转换器,但任何其他解串器库都适用于我)
// model/DailyStatsRecord.ts
export class DailyStatsRecord {
public uuid: string;
public date: string;
public additionalData: any;
}
// index.ts
import "reflect-metadata";
import {plainToClass} from "class-transformer";
import {DailyStatsRecord} from './model/DailyStatsRecord';
const instance = plainToClass(DailyStatsRecord, {
uuid: "faf9a028-5bbe-11ea-bc55-0242ac130003",
date: "2020-03-01",
otherField: 123,
more: ["data"],
foo: "bar",
});
console.log(JSON.stringify(instance.additionalData, null, 2));
Here is what I want this script to output:这是我希望此脚本输出的内容:
{
"otherField": 123,
"more": ["data" ],
"foo": "bar"
}
This can be accomplished without any third-party libraries, but you'll have to have pull the known properties out manually using object destructuring with a rest gather for the others and have the constructor take a parameter that is an object with the remaining key/values:这可以在没有任何第三方库的情况下完成,但是您必须使用对象解构手动提取已知属性,并为其他人使用休息收集,并让构造函数采用一个参数,该参数是一个带有剩余键的对象/价值观:
type POJO = {
[key: string]: any
};
class HasExtra {
public foo: string;
public bar: number;
public rest: POJO;
constructor(foo: string, bar: number, rest: POJO) {
this.foo = foo;
this.bar = bar;
this.rest = rest;
}
}
const dataFromJSON = {
foo: "hi",
bar: 3,
baz: true,
qux: null,
}
const {
foo,
bar,
...rest
} = dataFromJSON;
const instance = new HasExtra(foo, bar, rest);
console.log(instance.rest); // logs { baz: true, qux: null }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.