首页 > 解决方案 > json2typescript serializeObject 方法返回空对象

问题描述

我正在尝试将 Typescript Contact 类转换回 JSON,这可以根据“json2typscript”包的文档进行。

这不能通过返回 {}:

 try {
  const obj = new JsonConvert().serializeObject(contact);
  console.log(obj);
} catch (err) {
  console.error(err);
}

这是我试图映射的类:

@JsonObject('Contact')
export class Contact {

@JsonProperty('id', String, true)
id: string = undefined;

@JsonProperty('created', String, true)
created: string = undefined;

@JsonProperty('updated', String, true)
updated: string = undefined;

@JsonProperty('first_name', String, true)
firstName: string = undefined;

@JsonProperty('last_name', String, true)
lastName: string = undefined;

@JsonProperty('role', String, true)
role: string = undefined;

@JsonProperty('phone', String, true)
phone: string = undefined;

@JsonProperty('email', String, true)
email: string = undefined;

@JsonProperty('notes', String, true)
notes: string = undefined;

@JsonProperty('companies', [Company])
companies: [] = undefined;
}

关于如何做到这一点的任何想法?

标签: jsonangulartypescript

解决方案


作为这个拉取请求

如果您使用的对象不是映射类的真实实例,则应将第二个参数serializeObject作为引用类传递给:

jsonConvert.serializeObject(contact, Contact);

适用于 v1.3.0+


推荐阅读