简体   繁体   English

Angular 5将对象转换为嵌套JSON

[英]Angular 5 Convert Object to Nested JSON

I want to use Angular 5 HttpClient to send post request, but I am struggling casting object to nested JSON. 我想使用Angular 5 HttpClient发送帖子请求,但是我正在努力将对象转换为嵌套JSON。 For example, I have such class: 例如,我有这样的课:

export class Team {

    members: Person[];

    constructor(members: Person[]) {
            this.members = members;
    }
}

export class Person {

    name: string;
    gender: string;
    ...

    constructor(...) { ... }
}

ANd the expected JSON body should be something like this: 预期的JSON正文应如下所示:

{

    "members" : [
            {
                    "name" : someone01,
                    "gender" : ...,
                    ...
            },
            {
                    "name" : someone02,
                    "gender" : ...,
                    ...
            },
            ...
    ]
}

May I know how to do this? 我可以知道该怎么做吗? Thanks in advance. 提前致谢。

This sample would help, its a working example: 该示例将对其工作示例有所帮助:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  title = 'app';
   val =data.members;
}

export class Team {
  members: Person[]
}

interface Person {
  name: string;
  gender: string;
}

const data:Team ={
  "members" : [
          { 
                  "name" : 'someone01',
                  "gender" : 'm',

          },
          {
                  "name" : 'someone02',
                  "gender" : 'f',

          },
  ]
}

In order to display, you can make use of the following in you 'app.component.html': 为了显示,您可以在“ app.component.html”中使用以下内容:

<table>
      <tr *ngFor="let item of val">
        <td>{{item.name}}</td>
        <td>{{item.gender}}</td>
      </tr>

</table>

If your object model is same as json output then use json.stringify 如果您的对象模型与json输出相同,则使用json.stringify

const jsonstring = JSON.stringify(yourModel);

You could create nested json like this 您可以像这样创建嵌套的json

'members': membersCollection.map(element => ({
            'name': element.name,
            'gender': element.gender,
            'addresses: [element.Addresses.map(address=> ({
                        'city': address.cityName,
                        'country': address.country,
                        })]
        })),

I would also suggest you to breakdown nested classes to small methods, so might have better readability. 我还建议您将嵌套类分解为小方法,这样可能会提高可读性。

const body ={

'members' : [getMemebers(someClass)],
'addresses' : [getAddresses(someClass)],
};

make sure JSON is valid before using it. 在使用JSON之前,请确保其有效

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

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