JS 有哪些现成的库能够方便的对业务对象导出必要的属性(JSON)或导入 Json 对象?

2023-04-14 20:54:40 +08:00
 riceball

常见的,业务对象中的的某些属性需要导出为 JSON 对象,或者相反,将 Json 对象的值赋值(导入)给业务对象. 然而 Json 对象的属性名称并不一定是就是业务对象中的属性名称,也不是所有的 Json 对象的值都该被赋值(导入).

针对属性默认有如下的约定:

例如,假如能够用修饰器定义属性的话:

@Properties
export class ContactWay extends AbstractModel {
  @Property({alias:'启', type: 'Boolean', default: true}) enabled?: boolean;
  @Property({alias:'私', type: 'Boolean', default: true}) private?: boolean;
  @Property({alias:'类', type: 'String'}) category?: string;
  @Property({alias:'型', type: 'String'}) type?: string;
  @Property({alias:'值', type: 'String', encrypted: true}) value?: string | null;
  @Property({alias:'起日', type: 'Date'}) startTime?: string | null;
  @Property({alias:'止日', type: 'Date'}) endTime?: string | null;

  constructor(options?) {
    if (typeof options === 'string') options = {'值': options};
    super(options);
  }
}

@Properties
export class ContactPhone extends ContactWay {
  constructor(options?) {
    super(options);
    this['type'] = '电话';
  }
}

@Properties
export class ContactEmail extends ContactWay {
  constructor(options?) {
    super(options);
    this['type'] = '邮件';
  }
}

@Properties
export class ContactAddress extends ContactWay {
  @Property({alias:'国', type: 'String', encrypted: true}) country!: string;
  @Property({alias:'省', type: 'String', encrypted: true}) province!: string;
  @Property({alias:'市', type: 'String', encrypted: true}) city!: string;
  @Property({alias:'区', type: 'String', encrypted: true}) district!: string;
  @Property({alias:'镇', type: 'String', encrypted: true}) town!: string;
  @Property({alias:'邮编', type: 'String', encrypted: true}) zip!: string;

  constructor(options?) {
    super(options);
    this['type'] = '地址';
  }
}

@Properties
export class Contacts extends AbstractModel {
  @Property({alias:'电话', type: arrayOf(ContactPhone), encrypted: true}) phones!: ContactPhone[];
  @Property({alias:'地址', type: arrayOf(ContactAddress), encrypted: true}) addresses!: ContactAddress[];
  @Property({alias:'邮件', type: arrayOf(ContactEmail), encrypted: true}) emails!: ContactEmail[];
}

// 导入
const contacts = new Contacts({
  '电话': ['1234567890', {'私': false, '值': '010-1111111', '类': '单位'}],
  '地址': [{'国': '中国', '省': '福建', '市': '...'}],
  '邮件': ['ah@example.com']
})

// 导出
JSON.stringify(contacts)
{
  "电话": [{"值": "1234567890", "型": "电话"}, {"私": false, "值": "010-1111111", "类": "单位", "型": "电话"}],
  "地址": [{"国": "中国", "省": "福建", "市": "...", "型": "地址"}],
  "邮件": [{"值": "ah@example.com", "型": "邮件"}]
}
630 次点击
所在节点    问与答
1 条回复
riceball
2023-04-15 17:13:46 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/932629

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX