Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi could u please tell me how to convert this to a list? I encourage this error :
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.Net20.dll

Additional information: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[App_Code.APIResult]'.
every time I want to deserialize the response.
here is my response:
{"status":"Ok","rows":[{"elements":[{"status":"Ok","duration":{"value":10,"text":""},"distance":{"value":62,"text":"۷۵ متر"}}]}],"origin_addresses":["35.724098,51.424491"],"destination_addresses":["35.724165,51.425121"]}


What I have tried:

public class APIResult
   {
         public class Duration
         {
             public int value { get; set; }
             public string text { get; set; }
         }

         public class Distance
         {
             public int value { get; set; }
             public string text { get; set; }
         }

         public class Element
         {
             public string status { get; set; }
             public Duration duration { get; set; }
             public Distance distance { get; set; }
         }

         public class Row
         {
             public IList<Element> elements { get; set; }
         }

         public class Example    //{"status":"Ok", "rows":[                 {                     "elements":                     [{"status":"Ok",                     "duration":{"value":11,"text":""},                     "distance":{"value":62,"text":"۷۵ متر"}}                 ]}             ],       "origin_addresses":["35.724098,51.424491"],      "destination_addresses":["35.724165,51.425121"]}          }
         {
             public string status { get; set; }
             public IList<Row> rows { get; set; }
             public IList<string> origin_addresses { get; set; }
             public IList<string> destination_addresses { get; set; }
         }



private bool RequestTimeTrip2()
       {
           if (!mapNRPTTCEventWinService.ReqListInfo(dt_Main))
           {
               //errLog
               return false;
           }
           string[] arrLatLon = null;
           string strResult = string.Empty;
           for (int i = 0; i < dt_Main.Rows.Count; i++)
           {
               arrLatLon = dt_Main.Rows[i]["Points"].ToString().Split('^');
               for (int j = 0; j < arrLatLon.Length - 1; j++)
               {
                   var url = "https://api.neshan.org/v1/distance-matrix?origins=" + arrLatLon[j].Split(',')[0] + "," + arrLatLon[j].Split(',')[1] + "&destinations=" + arrLatLon[j + 1].Split(',')[0] + "," + arrLatLon[j + 1].Split(',')[1];
                   HttpClient client = new HttpClient();
                   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                   client.DefaultRequestHeaders.Add("Api-Key", "web.dSy4OSDOQtcMokSozr7qmAAvn55jSop5gX95PNTF");
                   var response = client.GetAsync(url).Result;
                   List<App_Code.APIResult> objApiResult = new List<APIResult>();
                   string result = response.Content.ReadAsStringAsync().Result;
                   // var responseString = new StreamReader(response.Content.ReadAsStreamAsync().Result).ReadToEnd();
                   StreamReader reader = new StreamReader(result);
                   result = reader.ReadToEnd();
                   objApiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIResult>>(result);




                   //  objApiResult = (App_Code.APIResult)Newtonsoft.Json.JsonConvert.SerializeObject(result);
                   //List<App_Code.APIResult> lstResult = JsonConvert.DeserializeObject<List<App_Code.APIResult>>(responseString);
                   // var lobjResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIResult>>(responseString);
                   //var lobjResult = JsonConvert.DeserializeObject<APIResult>(responseString);
                   // var deserialized = JsonConvert.DeserializeObject<IEnumerable<App_Code.APIResult>>(response.Content.ReadAsStringAsync().ToString());
                   //  var lobjResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIResult1>>(responseString);
               }
           }
           return true;
       }
Posted
Updated 19-Sep-18 0:04am
v2
Comments
Richard Deeming 20-Sep-18 10:08am    
The JSON you've shown is not a list of anything. It is a single object, which seems to match your Example nested class.
Newtonsoft.Json.JsonConvert.DeserializeObject<APIResult.Example>(result)

1 solution

I have a helper class in my article Working with JSON in C# & VB[^] that I tested your classes and raw JSON sample to be deserialized and works fine. Here is my code test:
C#
class Program
{
    static void Main(string[] args)
    {
        var rawJson = @"{""status"":""Ok"",""rows"":[{""elements"":[{""status"":""Ok"",""duration"":{""value"":10,""text"":""""},""distance"":{""value"":62,""text"":""۷۵ متر""}}]}],""origin_addresses"":[""35.724098,51.424491""],""destination_addresses"":[""35.724165,51.425121""]}";
        var result = JsonHelper.ToClass<Example>(rawJson);
    }
}

public class Duration
{
    public int value { get; set; }
    public string text { get; set; }
}

public class Distance
{
    public int value { get; set; }
    public string text { get; set; }
}

public class Element
{
    public string status { get; set; }
    public Duration duration { get; set; }
    public Distance distance { get; set; }
}

public class Row
{
    public IList<Element> elements { get; set; }
}

public class Example
{
    public string status { get; set; }
    public IList<Row> rows { get; set; }
    public IList<string> origin_addresses { get; set; }
    public IList<string> destination_addresses { get; set; }
}


public static class JsonHelper
{
    public static string FromClass<T>(T data, bool isEmptyToNull = false,
        JsonSerializerSettings jsonSettings = null)
    {
        string response = string.Empty;

        if (!EqualityComparer<T>.Default.Equals(data, default(T)))
            response = JsonConvert.SerializeObject(data, jsonSettings);

        return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
    }

    public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
    {
        var response = default(T);

        if (!string.IsNullOrEmpty(data))
            response = jsonSettings == null
                ? JsonConvert.DeserializeObject<T>(data)
                : JsonConvert.DeserializeObject<T>(data, jsonSettings);

        return response;
    }
}
 
Share this answer
 
Comments
Maciej Los 19-Sep-18 6:44am    
5ed!
Graeme_Grant 19-Sep-18 7:54am    
Thanks! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900