0

I'm looking into some old code and I am seeing something I cannot figure out. The code is a controller action that returns a dynamic object:

return new
{
    Result = true,
    Count = data.Count(),
    Students = data.Select(s => string.Format("{0}, {1}", s.LastName, s.FirstName))
};

However, the resulting JSON in the browser is not coming back as I would expect:

{
    "$id":"1",
    "Result":true,
    "Count":1,
    "Students":
    {
        "$id":"2",
        "$values":["USER, ACTIVE"]
    }
}

What I would expect, and what I normally get any other time I do this sort of thing, is more like this:

{
    "Result":true,
    "Count":1,
    "Students":
    {
        ["USER, ACTIVE"]
    }
}

I have no idea where the $id and $values properties are coming from. I haven't seen this happen before with .Net, so I'm not sure what is causing this. It's not the dynamic object return that's causing the problem because I switched it to a named type just to test it out and it still does the same thing.

Charles Boyung
  • 2,464
  • 1
  • 21
  • 31
  • This looks like a problem with serializer settings. Check out https://stackoverflow.com/questions/11542144/how-to-remove-id-during-json-serialization – Sergey Kudriavtsev Apr 18 '19 at 16:12

2 Answers2

1

You need add this line of code to Global.asax to avoid append $id

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
= Newtonsoft.Json.PreserveReferencesHandling.None;
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • Okay, that works IF I also change the action method to return an IHttpActionResult instead of a dynamic, and change the above code to `return Json(`. Any thoughts on how to make it work without that change? – Charles Boyung Apr 18 '19 at 16:39
  • Did you return model or object? If you return the DTO or model object you dont need that configure – Hien Nguyen Apr 18 '19 at 16:45
  • The code was returning exactly what I showed above. To make this configuration work, I had to wrap it in the Json() method. – Charles Boyung Apr 18 '19 at 17:02
-1

You need to have a .ToList() at the end of the students.

{
    Result = true,
    Count = data.Count(),
    Students = data.Select(s => string.Format("{0}, {1}", s.LastName, s.FirstName)).ToList()
};
user833831
  • 428
  • 3
  • 10
  • 1
    How would this remove the `$id` property? Anyway, adding `ToList` will have literally zero effect here. – DavidG Apr 18 '19 at 16:18