0

I have a TypeScript class named order. 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. 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}; and then later called JSON.stringify(order_json) to send it over an HTTP connection? My understanding is a JSON structure is simply a Javascript object in a particular format. Is this correct?

4
  • "can I simply do let order_json = {"order": order}; and then later called JSON.stringify(order_json) to send it over an http connection?". Have you tried yet? Commented Jul 22, 2016 at 17:11
  • I was able to get the first part to work. I don't have the POST set up yet in Angular so unable to test the stringify feature (Although it does look fine in the console), but the creation seems to work. I was expecting issues with this approach as it seemed too "simple"? Commented Jul 22, 2016 at 17:13
  • Doing class -> JSON is easy, but you can't automate the deserializing of a JSON to a specific case class I'm afraid. It's one of the many reasons classes suck :p You will have to write a deserializer yourself: MyClass.fromJson Commented Jul 22, 2016 at 17:41
  • I'm not worried about deserialization, but that's good to know. TypeScript has helped a Java programmer more easily ease his way into Javascript. Commented Jul 22, 2016 at 18:18

1 Answer 1

1

You don't need to stringify it send it over an HTTP connection. 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).

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:

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

// or $http.post(yourEndpoint, { order }); if using ecmascript6
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.