3

i'm using a WebApi to return a Json string, ' the returned string is Commented in the Code bellow '

private async void setDataContext()
    {
        var str = (await HttpVerbs.HttpGet("commandelist/1"));
        //"[{\"Num\":\"10\",\"NomRestau\":\"Woodpecker\",\"Date\":\"11/23/2013 6:02:00 PM\",\"Total\":\"200\",\"Etat\":\"False\"},{\"Num\":\"9\",\"NomRestau\":\"Woodpecker\",\"Date\":\"11/23/2013 6:02:00 PM\",\"Total\":\"200\",\"Etat\":\"False\"},{\"Num\":\"8\",\"NomRestau\":\"Woodpecker\",\"Date\":\"11/23/2013 6:02:00 PM\",\"Total\":\"200\",\"Etat\":\"False\"}]";

        cmdList = (ObservableCollection<CommandeList>)JsonConvert.DeserializeObject(str, typeof(ObservableCollection<CommandeList>));
        Listu.DataContext = cmdList;
    }

Here the HttpVerbs Class

public class HttpVerbs
{

    public static async Task<string> HttpGet(string url)
    {
        var httpClient = new HttpClient();

        return (await httpClient.GetStringAsync("http://{myWebSite}/api/" + url));
    }
}
  • if i assign directly the commented Json string to "str"(the variable) everything works ! but, if i try to get it from my webApi ( as i do in this code ) an exception is thrown

{Newtonsoft.Json.JsonSerializationException: Error converting value "[{"Num":"10","NomRestau":"Woodpecker","Date":"11/23/2013 6:02:00 PM","Total":"200","Etat":"False"},{"Num":"9","NomRestau":"Woodpecker","Date":"11/23/2013 6:02:00 PM","Total":"200","Etat":"False"},{"Num":"8","NomRestau":"Woodpecker","Date":"11/23/2013 6:02:00 PM","Total":"200","Etat":"False"}]" to type 'System.Collections.ObjectModel.ObservableCollection`1[RestO.Models.CommandeList]'. Path '', line 1, position 355.

Remark : my string contains 355 characters.

I used this as Model ""

public class CommandeList
{
    public string Num { get; set; }
    public string NomRestau { get; set; }
    public string Date { get; set; }
    public string Total { get; set; }
    public string Etat { get; set; }
}
James MACHOUK
  • 78
  • 1
  • 6

1 Answers1

0

Just guessing here, without seeing how you returning this string from WebApi. If your controller action method has return type of string, this won't work.

The proper way to return Json string is shown in this answer: Return a JSON string explicitly from Asp.net WEBAPI?

You need to pack it into HttpResponseMessage.

Community
  • 1
  • 1
mlusiak
  • 1,054
  • 14
  • 28