Search code examples
jsonasp.net-mvcformatjsonresult

asp.net mvc json result format


public class JsonCategoriesDisplay
    {
        public JsonCategoriesDisplay() { }

        public int CategoryID { set; get; }
        public string CategoryTitle { set; get; }
    }

    public class ArticleCategoryRepository
    {
        private DB db = new DB();  

        public IQueryable<JsonCategoriesDisplay> JsonFindAllCategories()
        {
            var result = from c in db.ArticleCategories                         
                         select new JsonCategoriesDisplay
                         {
                             CategoryID = c.CategoryID,
                             CategoryTitle = c.Title                            
                         };

            return result;
        }

          ....
    }

public class ArticleController : Controller
    {
        ArticleRepository articleRepository = new ArticleRepository();
        ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository();


        public string Categories()
        {
            var jsonCats = articleCategoryRepository.JsonFindAllCategories().ToList();

            //return Json(jsonCats, JsonRequestBehavior.AllowGet);

            return new JavaScriptSerializer().Serialize(new { jsonCats});
        }

    }

This results with following:

{"jsonCats":[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova
kategorija"},{"CategoryID":5,"CategoryTitle":"Testna
kategorija"}]}

If I use line that is commented and place JsonResult instead of returning string, I get following result:<

[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova
kategorija"},{"CategoryID":5,"CategoryTitle":"Testna
kategorija"}]

But, I need result to be formatted like this:

{'2':'Politika','3':'Informatika','4':'Nova
kateorija','5':'Testna kategorija'}

Is there a simple way to accomplish this or I will need to hardcode result?


Solution

  • Have a look at the Json.Net library

    The Json.NET library makes working with JavaScript and JSON formatted data in .NET simple. Quickly read and write JSON using the JsonReader and JsonWriter or serialize your .NET objects with a single method call using the JsonSerializer.

    I have successfully used it within a .net mvc project.