无法使用 JavascriptSerializer 将类型字符串隐式转换为列表

Cannot implicity convert type string to List use JavascriptSerializer

我尝试序列化我的手机列表

在我的应用程序中,我在我的控制器中使用 javascriptSerializer:

[HttpGet]
    public List<Phone> GetPhones()
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var serializedResult = serializer.Serialize(new TestPhoneService().GetTestData());
        return serializedResult;
    }

我的方法 GetPhones() 应该 return 电话 json 格式 ,但我有错误: 无法将类型 'string' 隐式转换为 'System.Collections.Generic.List... 可能有人知道我如何配置 javascript serializer 来解决错误?感谢您的回答!

您收到此错误是因为 JavascriptSerializer.Serialize(...) return 是 string 但您的方法 return 是电话列表。将 GetPhones() 的 return 类型更改为 string

要从操作方法 GetPhones() return Json 格式,将 return 类型从 List 更改为 ActionResult 或 JsonResult 类型。并使用 return Json(serializedResult) 而不是 return serializedResult;

目前,您的 GetPhones() 方法期望 List<Phone> 被 returned,但是您当前 returning Serialize() 的结果将产生 string.

的方法

如果你想明确地return一个List<Phone>,那么你根本不需要序列化你的内容,你可以简单地return collection如下:

[HttpGet]
public List<Phone> GetPhones()
{
    return new TestPhoneService().GetTestData();
}

同样,如果您想 return JSON 序列化版本的 collection,您可以尝试将 return 类型更改为 JsonResult 并且在 returning 你的 collection 时使用 Json() 方法:

[HttpGet]
public JsonResult GetPhones()
{
    return Json(new TestPhoneService().GetTestData());
}