7

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

4
  • 1
    Are you using JSON.Net library or a custom implementation? Check if the library can help - will save you a ton of time... Commented Apr 27, 2012 at 16:11
  • What are you defining as a nested string ? Commented Apr 27, 2012 at 16:13
  • 1
    @cWilk, You should post your code (expecting 1 or 2 lines) that shows what particular "pretty easily" way of creating JSON you pick. Commented Apr 27, 2012 at 16:16
  • return data from SP - created object listItem[] li = new listItem[count] - returnString = new JavaScriptSerializer().Serialize(li); return returnString Commented Apr 27, 2012 at 16:24

4 Answers 4

17

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"
                    }
                }
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

Not sure if this is quite what i'm after, I dont know how many nested levels there will be when make the call to the DB, Multiple objects , wtith potentially multiple objects
not checked the limits (if there are any but just opened an app where shipments have collections of items that have statuses with are all complex objects. seems to run fine
well that works.. give it a go, if your using MVC 3 hopefully it will be a quick test
I should probably give a bit more info , I query the DB bringing back say a list of 10 items , each have unique ID's and a parent keys, I want to build my object and then serialize into JSON, I beleive the building of the object and assigning the correct kids to correct parents is where my issue lies
I guess my question really is , how do you create the complex c# objects in the first place ?
|
5

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.

2 Comments

I should probably give a bit more info , I query the DB bringing back say a list of 10 items , each have unique ID's and a parent keys, I want to build my object and then serialize into JSON, I beleive the building of the object and assigning the correct kids to correct parents is where my issue lies
No problem--I've done the same myself in an app I worked on. I took the result from the DB and used it to create an anonymous class which I then passed to the serialization method. So for the "data" object above, you might construct it like this: new {a = reader.GetString(field1), b = reader.GetString(field2), c = reader.GetString(field3) }; Using an anonymous class declaration for the object you pass to the JavaScriptSerializer's Serialize method gives you easy control over what to include in the JSON and how it will be represented, without needing to create a named class.
3
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"
                     } 
}

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.