user3532246
user3532246

Reputation: 23

Linq to Json MVC 5 not formatting as expected

might seem really simple however I can't get my json to be correctly formatted from my MVC 5 controller.

My output is showing as;

[
   {
      "result":{
         "account_color":"B43104",
         "account_desc":"Welcome to XYZ",
         "account_name":"XYZ",
         "account_zone":1
      }
   },
   {
      "result":{
         "account_color":"FF0000",
         "account_desc":"Test Company",
         "account_name":"Test",
         "account_zone":2
      }
   }
]

So as you can see the level above result does not show any text so it seems like the 'result' section is getting added to a blank node

My controller is;

 public IEnumerable<dynamic> Get()
        {
            return db.tblAccounts.Select(o => new
            {
                result = new
                {
                    account_name = o.account_name,
                    account_desc = o.account_desc,
                    // account_image = Url.Content("~/images/") + String.Format("account_{0}.png", o.id),
                    account_color = o.account_color,
                }
            });
        }

My json formatter is;

config.Formatters.Clear();
            //config.Formatters.Add(new XmlMediaTypeFormatter());
            var json = new JsonMediaTypeFormatter();
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
            config.Formatters.Add(json);

so it just appears that the 'result' is at a sub level it needs to be a level higher, any help would be great.

Upvotes: 1

Views: 402

Answers (1)

kmacdonald
kmacdonald

Reputation: 3471

Try changing your code to look like this:

 public IEnumerable<dynamic> Get()
    {
        return db.tblAccounts.Select(o => 
            new
            {
                account_name = o.account_name,
                account_desc = o.account_desc,
                // account_image = Url.Content("~/images/") + String.Format("account_{0}.png", o.id),
                account_color = o.account_color,
            }
        );
    }

This will produce an array of results instead of the nested JSON that you provided. you don't actually need the result node label do you?

EDIT:

based on your response is this what you are looking for?

 public dynamic Get()
    {
        var accountsNode = new {
            accounts = db.tblAccounts.Select(o => 
                new
                {
                     account_name = o.account_name,
                     account_desc = o.account_desc,
                     // account_image = Url.Content("~/images/") + String.Format("account_{0}.png", o.id),
                     account_color = o.account_color,
                 }
            ).ToList()
        };
        return accountsNode;
    }

Upvotes: 1

Related Questions