Create nested json with c#

前端 未结 4 2005
日久生厌
日久生厌 2021-02-09 14:56

I am able to create a flat serialized JSON string pretty easily with c#

My issue is I want to create a nested string like this below

[ { 
    title: \"Y         


        
4条回答
  •  情歌与酒
    2021-02-09 15:35

    Are you using MVC 3? - Do something like:

    return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
    

    I use this to return complex C# objects that match the structure of the JavaScript objects I want.

    e.g.:

    var bob = new {
        name = "test",
        orders = new [] {
            new  { itemNo = 1, description = "desc" },
            new  { itemNo = 2, description = "desc2" }
        }
    };
    
    return Json(bob, JsonRequestBehavior.AllowGet);
    

    gives:

    {
        "name": "test",
        "orders": [
            {
                "itemNo": 1,
                "description": "desc"
            },
            {
                "itemNo": 2,
                "description": "desc2"
            }
        ]
    }
    

    EDIT: A bit more nesting for fun:

    var bob = new {
        name = "test",
        orders = new [] {
            new  { itemNo = 1, description = "desc" },
            new  { itemNo = 2, description = "desc2" }                  
        },
        test = new {
            a = new {
                b = new {
                    something = "testing",
                    someOtherThing = new {
                        aProperty = "1",
                        another = "2",
                        theThird = new {
                            bob = "quiteDeepNesting"
                        }
                    }
                }
            }
        }
    };
    
    return Json(bob, JsonRequestBehavior.AllowGet);
    

    gives:

    {
        "name": "test",
        "orders": [
            {
                "itemNo": 1,
                "description": "desc"
            },
            {
                "itemNo": 2,
                "description": "desc2"
            }
        ],
        "test": {
            "a": {
                "b": {
                    "something": "testing",
                    "someOtherThing": {
                        "aProperty": "1",
                        "another": "2",
                        "theThird": {
                            "bob": "quiteDeepNesting"
                        }
                    }
                }
            }
        }
    }
    

提交回复
热议问题