TecnoEye
TecnoEye

Reputation: 25

How to define a model class in angular8(TypeScript) or above for nested JSON response coming from SpringBoot backend code

I want to define a model class in angular8 for the below nested JSON response.

JSON Response:

{
  "message": "All Users fetched",
  "status": "Success",
  "data": [
    {
      "userid": "abc22",
      "password": "abc22",
      "role": 1,
      "sessionid": "AWS1",
      "sessiontype": "RC01",
      "status": null
    }
  ]
}

I am not sure how to do it for the nested JSON response. Could someone help me with it. Lets assume that all the datatypes of the above fields are String. Thanks in advance

Upvotes: 1

Views: 746

Answers (2)

ShamPooSham
ShamPooSham

Reputation: 2379

I assume you often have the response with message and status fields, but that the structure of the data field is different for different requests. In that case, I'd recommend you do a generic interface like this:

export interface ApiResponse<T> {
    message: string,
    status: "Success" | "Error", // Add more possible status responses if needed
    data: T
}

The user model would look something like this:

export interface User {
    userId: string,
    password: string,
    role: number,
    sessionid: string
    sessiontype: string,
    status: string // Or whatever type this should be
}

Now you can create a type alias like this:

type UserResponse = ApiResponse<User[]>

And use it with Angular's http service like this:

this.http.get<UserResponse>('/api/endpoint/to/userlist')
    .subscribe(resp => {
        console.log(resp.data) // This should print out the list of users
    })

*Edit* It should be noted that I'm using interfaces instead of classes, because that's usually what you want to do in angular. Interfaces don't generate any javascript code when compiled, they just help you with the typechecking during development. There will be no checking of the data structure during runtime, so if your response doesn't actually look like that you may run into problems.

Upvotes: 1

fredrik
fredrik

Reputation: 17617

You could do something like this:

class User {
    userId: string;
    password: string;
    role: number;
    sessionid: string;
    sessiontype: string;
    status: string;
}

class Response {
    message: string;
    status: string;
    data: User[];
}

const jsonData = {
  "message": "All Users fetched",
  "status": "Success",
  "data": [
    {
      "userid": "abc22",
      "password": "abc22",
      "role": 1,
      "sessionid": "AWS1",
      "sessiontype": "RC01",
      "status": null
    }
  ]
}

const response = new Response();
response.message = jsonData.message;
response.status = jsonData.status;
response.data = jsonData.data.map(userData => {
    const user = new User();
    user.userId = userData.userId;
});

Upvotes: 0

Related Questions