0

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; }        
    }
1
  • 1
    return Json(new { items = list }, JsonRequestBehavior.AllowGet); Commented Aug 23, 2016 at 3:46

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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; }
    }

1 Comment

Okay i create with as you say, but what next?I have same problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.