在我的应用程序中,我在我的控制器中使用javascriptSerializer:
[HttpGet]
public List<Phone> GetPhones()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(new TestPhoneService().GetTestData());
return serializedResult;
}
我的方法 GetPhones()应该以 json格式返回手机,但我有错误: 无法将类型'string'隐式转换为'System.Collections.Generic.List ... 可能有人知道我如何配置 javascript序列化程序来解决它的错误?谢谢你的回答!
答案 0 :(得分:1)
Currently, your GetPhones()
method is expecting a List<Phone>
to be returned, however you are currently returning the result of the Serialize()
method which is going to yield a string
.
If you want to explicitly return a List<Phone>
, then you don't really need to serialize your content at all and you could simply return the collection as follows :
[HttpGet]
public List<Phone> GetPhones()
{
return new TestPhoneService().GetTestData();
}
Likewise, if you wanted to return a JSON serialized version of your collection, you could try changing your return type to JsonResult
and using the Json()
method when returning your collection :
[HttpGet]
public JsonResult GetPhones()
{
return Json(new TestPhoneService().GetTestData());
}
答案 1 :(得分:0)
您收到此错误是因为JavascriptSerializer.Serialize(...)
返回string
,但您的方法会返回电话列表。将GetPhones()
的返回类型更改为string
。
答案 2 :(得分:0)
要从操作方法GetPhones()返回Json格式,请将返回类型从List更改为ActionResult或JsonResult类型。并使用return Json(serializedResult)而不是return serializedResult;