user2005657
user2005657

Reputation: 627

Uniting JsonResult why can't I get access through dynamic if the items are an anonymous type

I had a method looking like:

public JsonResult GetSpecies()
        {
            var species = new List<SpeciesType> {
                                                new SpeciesType{ Id=1, Name="Giraffe" },
                                                new SpeciesType{ Id=2, Name="Wolf" }
                                            };

            return Json(new { Species = species });
        }

Then I had the assembly this is in make its internals visible to my test project and had a test:

[TestMethod]
        public void GetSpecies_ReturnsJsonVersionOfNameAndId()
        {
            ...

            var result = controller.GetSpecies();

            dynamic data = result.Data;

            Assert.AreEqual(1, data.Species[0].Id);
            Assert.AreEqual("Giraffe", data.Species[0].Name);
            Assert.AreEqual(2, data.Species[1].Id);
            Assert.AreEqual("Wolf", data.Species[1].Name);
        }

So this worked fine.

I altered the method to return anonymous types in the array:

public JsonResult GetSpecies()
            {
                var species = new List<SpeciesType> {
                                                    new SpeciesType{ Id=1, Name="Giraffe" },
                                                    new SpeciesType{ Id=2, Name="Wolf" }
                                                }.Select(x => new { Id = x.Id, Name = x.Name });

                return Json(new { Species = species });
            }

The test now throws exceptions.

Can anyone explain why this is happening and how to fix?

Upvotes: 1

Views: 236

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500245

You're now not providing a List<T> - your Species property is just a sequence. I don't know how it's representing in JSON, and if it actually went across the wire, it might be okay - but it's probably simplest to just make sure that the Species value is actually a list:

var species = new List<SpeciesType> {
                                    new SpeciesType{ Id=1, Name="Giraffe" },
                                    new SpeciesType{ Id=2, Name="Wolf" }
                                }
    .Select(x => new { Id = x.Id, Name = x.Name })
    .ToList();

Upvotes: 3

Related Questions