简体   繁体   中英

Create nested json with c#

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: "Yes",
    id : "1",
    menu: [ { 
        title: "Maybe",
        id : "3",
        alert : "No",
        menu: [ {
            title: "Maybe Not",
            id : "8",
            alert : "No",
            menu: []
        } ]
    } ]
},
{
    title: "No",
    id : "2",
    menu: []
}]

Any help would be great

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.

eg:

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"
                    }
                }
            }
        }
    }
}

Try using

using System.Web.Script.Serialization;

//Assumed code to connect to a DB and get data out using a Reader goes here

Object data = new {
    a = reader.GetString(field1),
    b = reader.GetString(field2),
    c = reader.GetString(field3)
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(data);

This is built-in and saves you the work of serializing to JSON yourself!

This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.

using System.Web.Script.Serialization;
 


var strNJson = new
            {
                to = "hello",
                notification = new
                {
                    title = "textTitle",
                    body = "bodyText"
                }
            };
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            string json = javaScriptSerializer.Serialize(strNJson);
{   "to":"hello",
       "notification": {
                        "title":"titleText",
                         "body":"bodyText"
                     } 
}

You can make use of the ExpandoObject under the System.Dynamic namespace.

Here is a small snippet for achieving your solution:

dynamic parameters = new dynamic[2];

parameters[0] = new ExpandoObject();
parameters[0].title = "Yes";
parameters[0].id = "1";

parameters[0].menu = new dynamic[1];
parameters[0].menu[0] = new ExpandoObject();

parameters[0].menu[0].title = "Maybe";
parameters[0].menu[0].id = "3";
parameters[0].menu[0].alert = "No";
parameters[0].menu[0].menu = new dynamic[1];
parameters[0].menu[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].menu[0].title = "Maybe Not";
parameters[0].menu[0].menu[0].id = "8";
parameters[0].menu[0].menu[0].alert = "No";
parameters[0].menu[0].menu[0].menu = new dynamic[0];

parameters[1] = new ExpandoObject();
parameters[1].title = "No";
parameters[1].id = "2";
parameters[1].menu = new dynamic[0];


string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
Console.WriteLine(json);

Here is the work in fiddle

Note: There are other ways to achieve this, but I have been using this approach.

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