5

{Sorry new to JSON} I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)

My model is simply

public class ScheduleUsers
    {
        public string Resource{ get; set; }
}

On my controller

var users = new JsonArray(
               new JsonObject(
                new KeyValuePair<string,JsonValue>("id","1"),
                new KeyValuePair<string,JsonValue>("name","User1")),
                new JsonObject(
                new KeyValuePair<string, JsonValue>("id", "2"),
                new KeyValuePair<string, JsonValue>("name", "User2"))
                  );
            model.Resources = users.ToString();
D-W
  • 5,201
  • 14
  • 47
  • 74
  • 1
    I like anonymous types for quick projection, e.g. `return Json( new { foo = "bar" } )`. [Json.NET](http://james.newtonking.com/pages/json-net.aspx) is also quite popular and gives you numerous options. – Tim M. May 31 '13 at 06:22

2 Answers2

14

Why don't you just return a list of entities as a JSON result, like:

public class CarsController : Controller  
{  
    public JsonResult GetCars()  
    {  
        List<Car> cars = new List<Car>();
        // add cars to the cars collection 
        return this.Json(cars, JsonRequestBehavior.AllowGet);  
    }  
} 

It will be converted to JSON automatically.

L-Four
  • 13,345
  • 9
  • 65
  • 109
  • Ok so i did that, and changed model.Resources = GetResources().ToString(); but when looking at the html output i get resources:System.Web.Mvc.JsonResult – D-W May 31 '13 at 08:33
  • 2
    **add** `return this.Json(cars,JsonRequestBehavior.AllowGet );` otherwise you get [this](http://stackoverflow.com/questions/5588143/ef-4-1-code-first-json-circular-reference-serialization-error) error – Shaiju T Feb 01 '16 at 16:02
3

I did this and this works

    JavaScriptSerializer js = new JavaScriptSerializer();
                StringBuilder sb = new StringBuilder();
                //Serialize  
                js.Serialize(GetResources(), sb);



 public List<ScheduledResource> GetResources()
        {
            var res = new List<ScheduledResource>()
                {
                    new ScheduledResource()
                        {
                            id = "1",
                            color = "blue",
                            name = "User 1"
                        },
                    new ScheduledResource()
                        {
                            id = "2",
                            color = "black",
                            name = "User 2"
                        },

                };

            return res;
        }
D-W
  • 5,201
  • 14
  • 47
  • 74