0

I tryed Serialize my List of phones: enter image description here

in my application, i use javascriptSerializer in my controller:

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

My Method GetPhones() should return phones in json format, but i have error: Cannot implicitly convert type 'string' to 'System.Collections.Generic.List... May be somebody knows how i can configure javascript serializer for resolve it error ? Thanks for your Answers!

2
  • Serialize() returns a string therefore your serializedResult is a string and the return type of the method is List<Phone>. Change your method return type to string if that is what you need. Commented Apr 4, 2016 at 12:11
  • Thanks for your answer, but my method should return List. Commented Apr 4, 2016 at 12:28

3 Answers 3

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. for use your 1st example, i just wrote the next code in WebApiConfi.cs and config json and disable xml forrmatters: var json = GlobalConfiguration.Configuration.Formatters; json.JsonFormatter.UseDataContractJsonSerializer = true; json.Remove(json.XmlFormatter);
0

You get this error because JavascriptSerializer.Serialize(...) returns a string but your method returns a list of phones. Change the return type of GetPhones() to string.

Comments

0

To return Json format from the action method GetPhones(), change the return type from List to ActionResult or JsonResult type. And use return Json(serializedResult) instead of return serializedResult;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.