Angular 4 - JSON map for model and vice versa

I need to call [POST] a REST service from an Angular 4 application. The rest service expects JSON in the body of the request.

The JSON I create in Angular based on some user inputs looks something like this:

{
    "val-type": "prop",
    "val-name": "prop1",
    "op-ter": "DIFF",
    "value": "Unknown",
    "match-twice": false,
    "case-sensitive": false
}

      

In my code, I am creating this json as

let jsonSubpart = {
      "val-type": userInput.valtype,
      "val-name": userInput.valname,
      "op-ter": userInput.opter,
      "value": userInput.val,
      "match-twice": false,
      "case-sensitive": false
    }

      

I was hoping I could create a model for this structure to ensure that the json structure matches. So I went ahead and create a model.ts file as shown below

export class SubPart {
    public valType: string;
    public valName: string;
    public opTer: string;
    public value: string;
    public matchTwice: boolean = false;
    public caseSensitive: boolean = false;

    constructor(valType: string, valName: string, opTer: string, value: string,
        matchTwice: boolean, caseSensitive: boolean) {
        this.valType=valType;
        this.valName= valName;
        this.opTer=opTer;
        this.value = value;
        this.matchTwice=matchTwice;
        this.caseSensitive = caseSensitive;
    }
}   

      

My idea was to then use this model when building json -

import { Subpart} from './subpart.model.ts';

let jsonSubpart: Subpart = {
      "val-type": userInput.valtype,
      "val-name": userInput.valname,
      "op-ter": userInput.opter,
      "value": userInput.val,
      "match-twice": false,
      "case-sensitive": false
    }

      

However, this won't work as the field names in the json and the class are not the same. This way Angular would not know that the val type is the same as valType. I cannot store the variable names in the .ts file as val-type as this is not a valid variable name due to '-'.

I would like to hear from the experts what is the best approach in such a scenario? Should I just build the json without worrying about the class, or is there another way to get this kind of strong typing?

+3


source to share


1 answer


You can use Json typescript decorater to serialize your model at post time.

For example, declare the class as usual:

export class SubPart {
    @JsonProperty('val-type')
    public valType: string;
}

      

Fill in the model



  let jsonSubpart: Subpart = {
     valType: userInput.valtype
  }

      

and when publishing the model

 var json = serialize(jsonSubpart);

      

+3


source







All Articles