dragullar
dragullar

Reputation: 355

Convert Json to Object in Angular 7

This is json string {"firstName":"John" ,"lastName":"Doe" }. I would like to convert json string to object with custom name in angular.This is c# code.

public class Example
{ 
    [JsonProperty("firstName")]
    public string FName { get; set; }

    [JsonProperty("lastName")]
    public string LName { get; set; }
}

Upvotes: 0

Views: 220

Answers (2)

Rafael Pizao
Rafael Pizao

Reputation: 841

If you have a front-end model, use the classToPlain method of the lib class-transformer https://github.com/typestack/class-transformer

Example

import { classToPlain } from "class-transformer";
...
var yourModel: YourModel = {"firstName":"John" ,"lastName":"Doe" };
this.http.post(`${url}/AnyMethod`, classToPlain(yourModel)).pipe();
...

class YourModel{
   firstName: string;
   lastName: string;
}

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21638

Just use JSON.parse

console.log(JSON.parse('{"firstName":"John" ,"lastName":"Doe" }'))

But you shouldn't have to. How are you getting the JSON string? If you made a call to your C# api with the HttpClient like

http.get<YourModel>('apiUrl');

The response from the api should already be parsed as long as the api responded with a content type of text/json.

Upvotes: 2

Related Questions