Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - Map JSON to model and vice versa

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

The JSON which I am constructing in Angular, based on some user inputs looks something like

{
    "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 can create a model for this structure, to ensure that the json structure is adhered to. So, I went ahead and create a model.ts file as 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 constructing the 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 json and the class do not match. So, angular wouldn't know that val-type is the same as valType. I can't keep the variable names in .ts file as val-type as it's not a valid variable name due to a '-'.

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

like image 999
swati Avatar asked Feb 16 '26 01:02

swati


1 Answers

You can use Json typescript decorater to serialize your model while posting.

For example, declare class as usual:

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

Fill the model

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

and while posting the model

 var json = serialize(jsonSubpart);
like image 146
jitender Avatar answered Feb 18 '26 18:02

jitender