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'
},

Upvotes: 2

Views: 79

Answers (3)

Muhammad Waqas Aziz
Muhammad Waqas Aziz

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

Bijay Budhathoki
Bijay Budhathoki

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

Vishal Khatal
Vishal Khatal

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

Related Questions