Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I am using entity framework to get data from database and serialize it to JSON. And I want my JSON response looks like the one below. Shoud I add items property to my model and make JSON I want? Thanks.

Desired Json

{
      "items" : [
        {
          "Id": 1,
          "AdContent":"Content1"
        },
        {
          "Id": 2,
          "AdContent":"Content2"
        },
        {
          "Id": 3,
          "AdContent":"Content3"
        }   
      ]
}

Current JSON I receive

[
    {
        "Id":1,
        "AdContent":"Content1"
    },
    {
         "Id":2,
         "AdContent":"Content2"
    },
    { 
         "Id":3,
         "AdContent":"Content3"
    }
]

{

Controller

public JsonResult GetJson()
{
     using (var db = new DoskaUsContext())
     {
         List<AdViewModel> list = db.Ads.Select(x => new AdViewModel
         {
             Id = x.AdId,                    
             AdContent = x.AdContent
         }).ToList();

         return Json(list, JsonRequestBehavior.AllowGet);
     }
}

Model

 public class AdViewModel
    {
        public int Id { get; set; }
        public string AdContent { get; set; }        
    }
share|improve this question
1  
return Json(new { items = list }, JsonRequestBehavior.AllowGet); – Stephen Muecke Aug 23 at 3:46
up vote 3 down vote accepted

Anonymous object is one solution Json(new {items=list},...).

General approach to solve that problem - generate strongly typed classes with http://json2csharp.com/ and populate result via generated classes or at least see what is missing from your code.

In this particular case generated code:

public class Item
{
    public int Id { get; set; }
    public string AdContent { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Which shows missing piece of the puzzle - RootObject with list property items.

share|improve this answer

Create another model which hold collection of AdViewModel as items

 public class AdViewModel
    {
        public int Id { get; set; }
        public string AdContent { get; set; }        
    }

 public class NewModel
    {
        public AdViewModel items { get; set; }
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.