Reputation: 83
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'
},
Upvotes: 2
Views: 79
Reputation: 851
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);
Upvotes: 1
Reputation: 186
//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
Upvotes: 1
Reputation: 119
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 !!!
Upvotes: 1