2

When I get the data from the json I first create a class and define all the variables I get in json for strict data type like my json file is

 {"fname":"Mark","lname":"jhony"}

so in angular i make the class like this

export class user{

 fname: string;
 lname : string;
}

I am confuse how to make the class for the following json data

{"fname":"Mark","lname":"jhony",
 "parcels":[
   {
    "parcelId":123,
    "parcelName :"asd",
    "parcelItems:[
       { 
        "itemId":2,
        "itemName":"perfume"
       },
       { 
         "itemId":4,
         "itemName":"soap"
       }
     ]
]}

I tried to add array in the class but not getting what would be the best way to handle it in angularjs.

Giannis
  • 1,790
  • 1
  • 11
  • 29
Uahmed
  • 1,847
  • 5
  • 29
  • 45

2 Answers2

3

Typically you would use an interface to represent a data structure of primitive values, for example:

interface ParcelItem {
  itemId: number;
  itemName: string;
}
interface Parcel {
  parcelId: number;
  parcelName: string;
  parcelItems: ParcelItem[];
}
interface User {
  fname: string;
  lname: string;
  Parcels: Parcel[];
}

Depending upon how you acquire the JSON and parse it you can specify the interface to use. The most simplistic example would be:

const user = JSON.parse(userJson) as User;

If you want to use a class perhaps for associated methods for data manipulation, you have to instantiate the class using a constructor. This might look like:

const userValues = JSON.parse(userJson);
const user = new User(userValues);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Important thing to note: this does not in any way *validate* the JSON. This means that later down the line you may get runtime error saying for example that the `lname` is undefined. The typing only verifies that the TypeScript code is consistent with it self at compile time. Nothing is known about runtime. As a TypeScript newb I had to have a colleague explain this to me until I understood that there is no *validation* in this pattern. He also mentioned that people specify their JSON using some other tools which then generate the TypeScript types. – Peter Lamberg Dec 15 '19 at 15:45
  • Here is a question with several answers on what to do if also *runtime* validation is needed: https://stackoverflow.com/questions/33800497/check-if-an-object-implements-an-interface-at-runtime-with-typescript And another question: https://stackoverflow.com/questions/14425568/interface-type-check-with-typescript – Peter Lamberg Dec 15 '19 at 15:55
0

This would work.

export interface ParcelItemType {    
    itemId: number;
    itemName: string;
}

export interface ParcelType {
    parcelId: number;
    parcelName: string;
    parcelItems: ParcelItemType[];
}

export interface YourType {
   fname: string;
   lname: string;
   parcels: ParcelType[];
}
Ntwobike
  • 2,406
  • 1
  • 21
  • 27