'how to do Json form MVC model
I have this models, I try to serialize as Json
public class a
{
public String Name{ get; set; }
public String LastName{ get; set; }
}
I would to have a Json like this
{
id:1,
name:'Name',
description:'Erika'
},
{
id:2,
name:'LastName',
description:'Conor'
},
Solution 1:[1]
You need to create the class like
public class YourClassName
{
public int id{ get; set; }
public String name{ get; set; }
public String description{ get; set; }
}
then you have serialize it using below code :
var result = JsonConvert.SerializeObject(YourClassName);
hope this helps !!!
Solution 2:[2]
//declare a static list of a class to model
static List<a> _results = new List<a>
{
new a{
id:1,
name:'Name',
description:'Erika'},
new a{
id:2,
name:'LastName',
description:'Conor'
}
};
//then add this ActionResult Action in controller which will return JSON Data
public ActionResult ReturnJson()
{
return Json(_results, JsonRequestBehavior.AllowGet);
}
//Best of Luck
Solution 3:[3]
Change your class to include three properties
public class YourClassName
{
public int id{ get; set; }
public String name{ get; set; }
public String description{ get; set; }
}
then
in whatever controller you are, on top
using System.Web.Script.Serialization;
in action
List<YourClassName> objs = new List<YourClassName>();
YourClassName obj = new YourClassName
{
id=1,
name = "Name",
description = "Erika"
};
YourClassName obj1 = new YourClassName
{
id = 2,
name = "LastName",
description = "Conor"
};
objs.Add(obj);
objs.Add(obj1);
var jasonSerializedObjs = new JavaScriptSerializer().Serialize(objs);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vishal Khatal |
| Solution 2 | |
| Solution 3 |
