0

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; }
}
dragullar
  • 345
  • 3
  • 5
  • 19
  • 1
    Try the below link, https://stackoverflow.com/questions/40421100/how-to-parse-a-json-object-to-a-typescript-object – Arun Prasat Jun 25 '19 at 04:01
  • This question has nothing to do with Angular. This is all about how to get your .NET API to serialise your models with custom naming attributes. – Adrian Brand Jun 26 '19 at 02:49

2 Answers2

2

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.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

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;
}
Rafael Pizao
  • 742
  • 8
  • 21