Search code examples
c#jsonobjecthttpclient

What is the best way to Deserialize an object from json to a class?


I am implementing a system for GPS Tracking, through the consumption of a web service api.

ERROR :

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TrackingRequest.Devices' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

This is in a web form application in c# with HttpClient using json of Newtonsoft.

My code

using (HttpClient clientKey = new HttpClient())
                   {
                        clientKey.BaseAddress = new Uri("http://api.trackingdiary.com/");
                        clientKey.DefaultRequestHeaders.Add("Hive-Session", key);
                        clientKey.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        HttpResponseMessage responseKey = clientKey.GetAsync("/v2/geo/devices/list").Result;
                        using (HttpContent contentkey = responseKey.Content)
                       {
                            Task<string> resultKey = contentkey.ReadAsStringAsync();
                            Devices obj = JsonConvert.DeserializeObject<Devices>(resultKey.Result);

                           Console.WriteLine();
                       }
                   }

My Class:

    class position
    {
        [JsonProperty("lat")]
        public int lat { get; set; }
        [JsonProperty("lng")]
        public int lng { get; set; }
        [JsonProperty("hdop")]
        public int hdop { get; set; }
        [JsonProperty("fix")]
        public bool fix { get; set; }
    }

    class Devices
    {
        [JsonProperty("id")]
        public int id { get; set; }
        [JsonProperty("name")]
        public string name { get; set; }
        [JsonProperty("date_contacted")]
        public string date_contacted { get; set; }
        [JsonProperty("startup")]
        public string startup { get; set; }
        [JsonProperty("position")]
        public position position { get; set; }    
    }
}

I want in objects to perform in DataTable.

JSON EXAMPLE JSON EXAMPLE


Solution

  • It looks like your JSON string contains an array of objects of the type in question. You are trying to deserialize it into a single instance, hence the error.

    Try this:

    IEnumerable<Devices> devices = JsonConvert.DeserializeObject<IEnumerable<Devices>>(resultKey.Result);
    

    And please rename the class to singular since it appears to represent a single Device.