简体   繁体   English

如何使用周围的字符串将Typescript类转换为JSON?

[英]How to convert typescript class into JSON with surrounding string?

I have a TypeScript class named order. 我有一个名为order的TypeScript类。 The generic structure is as follows: 通用结构如下:

export class Order {
    orderId : number= "";
    email : string = "";
    storeId : string = "";
    date : string = "";
    billing_address : Object = {};
    systemId : string = "";
    shipments : Object = {};
}

I want a way to convert this class into a JSON structure with a "order" key and the value being the fields of the order class. 我想要一种使用“订单”键将该类转换为JSON结构的方法,该值是订单类的字段。 So it can look like this: 所以它看起来像这样:

{
  "order":{
    "orderId":1232332,
    "date": "06/02/2016,
    etc....
   }
}

After doing a quick test while writing this question, can I simply do let order_json = {"order": order}; 在编写此问题进行快速测试之后,我可以简单地let order_json = {"order": order}; and then later called JSON.stringify(order_json) to send it over an HTTP connection? 然后再调用JSON.stringify(order_json)以通过HTTP连接发送它? My understanding is a JSON structure is simply a Javascript object in a particular format. 我的理解是JSON结构只是特定格式的Javascript对象。 Is this correct? 这个对吗?

You don't need to stringify it send it over an HTTP connection. 您无需对其进行字符串化即可通过HTTP连接发送它。 In most cases (depending on the framework you're using), if the response header is application/json and you just pass a plain old JavaScript object, whatever implementation you're using will generally take care of the encoding for you (this is unless you're dealing with an extremely low-level interface, which it doesn't appear that you are). 在大多数情况下(取决于您使用的框架),如果响应头是application/json而您只是传递了一个普通的旧JavaScript对象,则无论您使用哪种实现,通常都会为您处理编码(这是除非您要处理的是一个非常低级的接口,否则您似乎并没有。)

Just do something like this: 只是做这样的事情:

let order_json = { order: order };

WhateverHTTPLibraryYoureUsing.send(order_json);

You mentioned Angular in the comments, so that would look something like: 您在评论中提到了Angular,因此看起来像这样:

$http.post(yourEndpoint, { order: order });

// or $http.post(yourEndpoint, { order }); if using ecmascript6

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

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