简体   繁体   English

在 Angular 7 中将 Json 转换为对象

[英]Convert Json to Object in Angular 7

This is json string {"firstName":"John" ,"lastName":"Doe" }.这是 json 字符串 {"firstName":"John" ,"lastName":"Doe" }。 I would like to convert json string to object with custom name in angular.This is c# code.我想将 json 字符串转换为 angular 中具有自定义名称的对象。这是 c# 代码。

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

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

Just use JSON.parse只需使用 JSON.parse

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

But you shouldn't have to.但你不应该这样做。 How are you getting the JSON string?你是如何获得 JSON 字符串的? If you made a call to your C# api with the HttpClient like如果您使用 HttpClient 调用 C# api,例如

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.只要 api 以 text/json 的内容类型响应,就应该已经解析了来自 api 的响应。

If you have a front-end model, use the classToPlain method of the lib class-transformer https://github.com/typestack/class-transformer如果你有前端模型,使用lib class-transformer https://github.com/typestack/class-transformer的classToPlain方法

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM