简体   繁体   English

将 JSON 对象数组解析为 TypeScript 对象数组

[英]Parse array of JSON objects to array of TypeScript objects

I have an endpoint that returns this Json:我有一个返回此 Json 的端点:

{
  "result": [
    {
      "id": 1,
      "name": "Kayak",
      "category": "Watersports",
      "description": "A boat for one person",
      "price": 27500,
      "currencyCode": "EUR"
    },
    {
      "id": 2,
      "name": "Lifejacket",
      "category": "Watersports",
      "description": "Protective and fashionable",
      "price": 48095,
      "currencyCode": "EUR"
    },
    {
      "id": 3,
      "name": "Soccer Ball",
      "category": "Soccer",
      "description": "FIFA-approved size and weight",
      "price": 1950,
      "currencyCode": "EUR"
    }
]
}

I have a class called Product in Angular:我在 Angular 中有一个名为Product的类:

import { Money, Currencies } from 'ts-money';

export class Product {
private money: Money;
public Amount = this.money.amount;

public constructor(
    public Id: number,
    public Name: string,
    public Category: string,
    public Price: number,
    public Description: string,
    public CurrencyCode: string) {
        this.money = new Money(Price, CurrencyCode);
    }

public GetPrice(): Money {
    return this.money;
}
}

I made this code in Angular:我在 Angular 中编写了这段代码:

export class ProductComponent implements OnInit {

  constructor(private datasource: ProductDataSource) {
  }

  private products: Product[];

  ngOnInit(): void {
    this.datasource.GetProducts()
    .subscribe((data) => {
        this.products = data;
    });
  }
 }
}

This code successfully returns an array of JSON objects that have the same properties as Product .此代码成功返回与Product具有相同属性的 JSON 对象数组。 Now, when I subscribe to this observable:现在,当我订阅这个 observable 时:

this.datasource.GetProducts()
.subscribe((data) => {
    // this.products is a class property of type Product[]
    this.products = data; // How do I make this work?
});

I can not figure out how to make the transition from JSON object to Angular class.我不知道如何从 JSON 对象过渡到 Angular 类。 My HTML page does not recognize this.products as an array of Product objects.我的 HTML 页面无法将this.products识别为Product对象的数组。 What do I do?我该怎么办?

I think it's because of your mapping in your product class and also the type of your class, try to change class Product to interface Product我认为这是因为您在产品类中的映射以及类的类型,请尝试将类 Product 更改为接口 Product

like this像这样

    export interface Product{

    public id: number;
    public name: string;
    public category: string;
    public price: number;
    public description: string;
    public currencyCode: string; 

 }

you can go take a look at Angular : Class and Interface for the differences between class and interface您可以查看Angular : Class and Interface以了解类和接口之间的差异

EDIT : (as you can see in my code, I also changed the variable name to match with your JSON response)编辑:(如您在我的代码中所见,我还更改了变量名称以与您的 JSON 响应匹配)

Another approach could be to make JSON data, compatible with your Product class.另一种方法是使JSON数据与您的Product类兼容。 You could use the map rxjs operator to transform your JSON data into Product .您可以使用map rxjs 运算符将您的 JSON 数据转换为Product Modify the get products code, like this修改get products代码,像这样

 const source$ = of(result).pipe(pluck('result'),map(item=> item.map(x=>{ let product = new Product(x.id,x.name, x.category, x.price, x.description, x.currencyCode); return product; })));

Here is a StackBlitz link.这是一个StackBlitz链接。

Product properties names and json properties names doesn't match. Product属性名称和 json 属性名称不匹配。 You can do it like this:你可以这样做:

this.datasource.GetProducts()
  .subscribe((data) => {
    // this.products is a class property of type Product[]
    this.products = (data || []).map(item => new Product(item.id, item.name, item.category, item.price, item.description, item.currencyCode))
  });

create product interface with variables and use that interface to create array使用变量创建产品接口并使用该接口创建数组

    export interface Product{
      public Id: number,
      public Name: string,
      public Category: string,
      public Price: number,
      public Description: string,
      public CurrencyCode: string
    }

     products:Product[];

Change class to interface and change the case of also.将类更改为接口并更改也的大小写。

export interface Product{

public id: number;
public name: string;
public category: string;
public price: number;
public description: string;
public currencyCode: string; }

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

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