Question

I have a json string of format

{
"code": 0,
"message": "success",
"data": [
    {
        "data": 10,
        "total": 1000
     }
],
"page": {
    "page": 1,
    "per_page": 200,
}
}

I just tried to convert it to convert it as a json by the following code,

    public class Invoice
    {
        public int data {get; set;}
        public int total { get; set; }
    }

    public class Page
    {
        public int page { get; set; }
        public int per_page { get; set; }
    }

    public class RootObject
    {
        public int code { get; set; }
        public string message { get; set; }
        public List<Lisst> Lisst{ get; set; }
        public Page Page{ get; set; }
    }
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var request = HttpWebRequest.Create(uri) as HttpWebRequest;
        request.Accept = "application/json;odata=verbose";
        request.Method = "GET";

        request.BeginGetResponse(new AsyncCallback(GotResponse), request);
    }
    private void GotResponse(IAsyncResult asyncResult)
    {
        try
        {
            string data;
            HttpWebRequest myhttpwebrequest = (HttpWebRequest)asyncResult.AsyncState; ;
            using (HttpWebResponse response = (HttpWebResponse)myhttpwebrequest.EndGetResponse(asyncResult))
            {
                System.IO.Stream responseStream = response.GetResponseStream();
                using (var reader = new System.IO.StreamReader(responseStream))
                {
                    data = reader.ReadToEnd();
                }
                responseStream.Close();
            }
            this.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(data);
                });

                var myObjects = JsonConvert.DeserializeObject<RootObject>(data);

        }
        catch (Exception e)
        {
            var we = e.InnerException as WebException;
            System.Diagnostics.Debug.WriteLine("error : "+ we);
            if (we != null)
            {
                var resp = we.Response as HttpWebResponse;
                var code = resp.StatusCode;
                this.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Bye");
                    });
            }
            else
                throw;
        }

when i run this code , The expected output is stored as a string in data, but while running the line

var myObjects = JsonConvert.DeserializeObject<RootObject>(data);

i get an error stating that An exception of type 'System.FormatException' occurred in Newtonsoft.Json.DLL but was not handled in user code... is this the correct way to store as a key value pair??

Was it helpful?

Solution

It's simply a format exception (exactly as it says). JSON is formatted incorrectly so it 'cannot read it' when attempting to deserialize it into RootObjects.

See the following site for basic json validation to see where in this string of JSON there are misplaced characters etc.

http://jsonformatter.curiousconcept.com/

Paste your JSON into there and you'll see there are several errors.

NOTE: I'm not implying AT ALL that this is a way of validating your JSON during development in the future. I'm saying, in this case, it's a way I've isolated the cause of your exception. There are clearly issues with the way in which the source of JSON (the 'unserialized' object) is rendering out.

Also, as a side note, these sorts of exceptions should not be unhandled. Get some appropriate try catch blocks in there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top