I have this model:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public List<Color> Colors { get; set; }
}
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
and asp.net MVC's return Json(...)
gives me this:
[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":29,"Colors":[{"ColorId":2,"Name":"Blue"}]}]
when I try to return a type of: List<Person>
but I want something like this (if possible):
{"People":[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},{"Name":"Albert","Age":83,"Colors":[{"ColorId":2,"Name":"Blue"}]}]}
MY QUESTION(S):
How can I make C# (asp.net mvc) return JSON with a better format of something like: (note: ignore the data, my main point is for it to return with "People" as the main collection.. how should I do this? JSON.net?)
{"People":[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]}, {"Name":"Albert","Age":83,"Colors":[{"ColorId":2,"Name":"Blue"}]}]}
OR how can I make KNOCKOUT.JS MAPPING PLUGIN work with this type of JSON format? (for those who know knockout)
[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]}, {"Name":"Albert","Age":29,"Colors":[{"ColorId":2,"Name":"Blue"}]}]
UPDATE (extra clarification/info):
this is my data, and I want to return a List
private List<Person> _people = new List<Person>
{
new Person
{
Name = "JC",
Age = 24,
Colors = new List<Color>
{
Red,
Blue,
}
},
new Person
{
Name = "Albert",
Age = 29,
Colors = new List<Color>
{
Blue
}
}
};
in a JSON format similar to this:
{"People":[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":83,"Colors":[{"ColorId":2,"Name":"Blue"}]}]}
i'm just wondering if that is possible, or if not, then how can I make the knockout.js mapping plugin adapt to MVC's way of returning json?
You need a container since you do not want to return an array but an object with a People variable.
Something like this (using dynamic):
Update
JSON is really simple format. Let's skip everything that you don't need to now.
{}
. Anything in them corresponds to properties in C#.IEnumerable
will return an array. An array can contain other arrays, objects or simple fields.The code above is using a dynamic object in C# and can be translated into a class looking like this:
Hence it's an object returning an array resulting in:
Where the
{}
corresponds toMyCustomClass
.you can return things, in for example, this way:
Maybe something like that :)