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; }
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

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.