简体   繁体   English

将 Typescript class 转换为字符串?

[英]Cast a Typescript class to a string?

I have a Typescript interface that I need to convert to a string to send to an API endpoint.我有一个 Typescript 接口,我需要将其转换为字符串以发送到 API 端点。

This is the object (as printed from the console using console.log()这是 object(从控制台使用console.log()

{name: "John", avatarId: 1, forwardRelationship: "WIFE", reverseRelationship: "HUSBAND"} {name:“John”,avatarId:1,forwardRelationship:“WIFE”,reverseRelationship:“HUSBAND”}

I initially tried JSON.stringify() to turn it into a string that the API would be happy with which outputs the following:我最初尝试JSON.stringify()将其转换为 API 会满意的字符串,输出以下内容:

{"name":"John","avatarId":1,"forwardRelationship":"WIFE","reverseRelationship":"HUSBAND"} {"name":"John","avatarId":1,"forwardRelationship":"WIFE","reverseRelationship":"HUSBAND"}

The API needs just the one string though so: API 只需要一个字符串:

"{name:John,avatarId:1,forwardRelationship:WIFE,reverseRelationship:HUSBAND}" “{name:John,avatarId:1,forwardRelationship:WIFE,reverseRelationship:HUSBAND}”

Is there a function I do this with shorthand?有没有 function 我用速记做这个? Or do Need to build the string up manually using each property?还是需要使用每个属性手动构建字符串?

I would recommend you to change the backend to accept valid JSON.我建议您更改后端以接受有效的 JSON。 If you really need to use this format you could use the following method:如果您确实需要使用这种格式,您可以使用以下方法:

   const text: string = "\"" + JSON.stringify(yourObject).replace(/"/g,"") + "\"";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM