Search code examples
c#jsonasp.net-mvcjson-deserialization

JSON deserialize array of long to list<long> not working


I have a controller giving JSON as response.

public ActionResult Messages()
{
   var Ids = new List<long>() { 1,2,3,4 };
   var data = JsonConvert.SerializeObject(Ids);
   return Json(data, JsonRequestBehavior.AllowGet);
}

Results in this JSON being responded:

[1,2,3,4]

At the client-side I'm trying to deserialize that JSON back to a List using :

using (_HttpResponse = client.SendAsync(_HttpRequest).Result)
{
    _HttpResponse.EnsureSuccessStatusCode();
    var _ResponseContent = await _HttpResponse.Content.ReadAsStringAsync();
    var Ids = JsonConvert.DeserializeObject<List<long>>(_ResponseContent);
}

_ResponseContent becomes:

"[1,2,3,4]"

Mark the " around the array. At deserialization I get the following exception :

Error converting value "[1,2,3,4]" to type 'System.Collections.Generic.List`1[System.Int64]'. Path '', line 1, position 11.

Any suggestions ?


Solution

  • JsonConvert.SerializeObject method convert your list of numbers to be a JSON string and you are returning that string from your action method. So basically your output is not really a json array of numbers, but a string like this

    "[1,2,3,4]"
    

    You should simply use the Json method which returns the correct json array

    public ActionResult Messages()
    {
        var Ids = new List<long>() { 1, 2, 3, 4 };
        return Json(Ids, JsonRequestBehavior.AllowGet);
    }
    

    This method should return a response like this

    [1,2,3,4]
    

    With this response, your other client code should be able to properly deserialize it to a list of numbers