简体   繁体   中英

JSON to typescript class, interface?

I am trying to develop a weppapp with Angular2 & Typescript. I have a json like this :

{
"homeMenu":{
    "aname1":{
        "title":"text",
        "route":"myroute"
    },
    "aname2":{
        "title":"text",
        "route":"myroute"
    },
    "aname3":{
        "title":"text",
        "route":"myroute"
    },
    "aname4":{
        "title":"text",
        "route":"myroute",
        "homeMenu":{
            "aname41":{
                "title":"text",
                "route":"myroute"
            },
            "aname42":{
                "title":"text",
                "route":"myroute"
            }
        }
    },
    "aname5":{
        "title":"text",
        "route":"myroute"
    }
}}

I want with some class or interface i don't know, generate this type of json. I tried but no success, for me I need 3 one with all menu, a class menu, and class submenu. i have something little similar but i don't have for example "aname1", "aname2" on my json...

at the beginning I thought it was not a valid JSON I have test with a json validator and he is valid. So i need some help to achieve this thanks :)

Based on your json and the answers to my comments, using interfaces you can do:

interface HomeMenu {
    [name: string]: MenuItem;
}

interface MenuItem {
    title: string;
    route: string;
    homeMenu?: HomeMenu;
}

interface Menu {
    homeMenu: HomeMenu;
}

let json: Menu = {
    "homeMenu": {
        "aname1": {
            "title": "text",
            "route": "myroute"
        },
        "aname2": {
            "title": "text",
            "route": "myroute"
        },
        "aname3": {
            "title": "text",
            "route": "myroute"
        },
        "aname4": {
            "title": "text",
            "route": "myroute",
            "homeMenu": {
                "aname41": {
                    "title": "text",
                    "route": "myroute"
                },
                "aname42": {
                    "title": "text",
                    "route": "myroute"
                }
            }
        },
        "aname5": {
            "title": "text",
            "route": "myroute"
        }
    }
}

( code in playground )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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