Iñigo
Iñigo

Reputation: 2016

How to represent nested JSON in Angular Classes?

I get this JSON from a server:

"Body": {
    "ErrorsContent": {
        "FunctionalError": [
            {
                "Code": "110900",
                "Error": "xx",
                "Position": "xx",
                "Value": ""
            },
            {
                "Code": "110900",
                "Error": "xx",
                "Position": "xx",
                "Value": ""
            },
            {
                "Code": "110900",
                "Error": "xx",
                "Position": "xx",
                "Value": ""
            },
            {
                "Code": "110902",
                "Error": "xx",
                "Position": "xx",
                "Value": ""
            },
            {
                "Code": "110900",
                "Error": "xx",
                "Position": "xx",
                "Value": ""
            }
        ]
    }
}

I need it to parse to an Angular object, so I created a couple classes:

export class Body{
    public ErrorsContent: ErrorsContent;
}

class ErrorsContent{
    public FunctionalError: FunctionalError;
}

class FunctionalError{
    public Code: any;
    public Error: any;
    public Position: any;
    public Value: any;
}

But this does not work fine when I have more than one FuntionalError.

How can I set the FuntionalError class so that I can have more than one error without being a class itself?

Any advice is welcome! Thanks.

Upvotes: 2

Views: 858

Answers (3)

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

class ErrorsContent{
    public FunctionalError: Array<FunctionalError>;
}

Upvotes: 2

Iftifar Taz
Iftifar Taz

Reputation: 839

FunctionalError is an array. You are declaring it as a object.

Use

class ErrorsContent {
    public FunctionalError: FunctionalError[];
}

instead of

class ErrorsContent {
    public FunctionalError: FunctionalError;
}

You can use any online tool to convert server JSON response to TS classes. Ex: jsontots, json2ts etc.

Upvotes: 3

jitender
jitender

Reputation: 10429

Change your ErrorsContent class to

class ErrorsContent{
    public FunctionalError: FunctionalError[];//it should be array 
}

Upvotes: 4

Related Questions