Get data from JsonResult

依然范特西╮ 提交于 2021-01-29 06:30:40

问题


The code is in ASP.NET Core. MVC controller returns Json(someData). I am trying to retrieve the data in the Unit test. The best I can do is to have

string data = JsonConvert.SerializeObject(jsonResult.Value);

and then compare the string. But I would prefer to get an object or an array to be able to do some more specific comparisons. Interesting, under debugger I can see that jsonResult.Value is of type Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<MyType> and there is even Results View that warns not to expand it or else; and if I expand it, I get exactly what I want! In my case it is a 4-element array of MyType objects. However, if I do something like from i in jsonResult.Value select i I get an error

Could not find an implementation of the query pattern for source type 'object'. 
'Select' not found

I hope there is a better way than comparing a JSON string!


回答1:


Try using Cast method

(from i in jsonResult.Value.Cast<MyType>() select i)

Edit: updated answer

 from i in ((IQueryable< MyType >)js.Value) select i


来源:https://stackoverflow.com/questions/38537861/get-data-from-jsonresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!