Nida Akram

Nida Akram

  • 1.9k
  • 2
  • 1.5k

Deserlizing json array into object

Jan 25 2019 7:21 AM
I am struggling with converting a json array returned from httpclient into object. I have tried many things and ended up using DataContractJsonSerializer. Problem is that when I try this it gives an error 
    Message = "There was an error deserializing the object of type There are multiple root elements."
 
Code for my deserilizing is 
 
 
           
  1. var urlPath = Url + "api/crm/gettripdata?regno="+regno;  
  2.             _httpClient.DefaultRequestHeaders.Authorization =  
  3.                      new AuthenticationHeaderValue("Bearer", accessToken);  
  4.             _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  5.               
  6.             HttpResponseMessage response = _httpClient.GetAsync(urlPath, HttpCompletionOption.ResponseContentRead).Result;  
  7.             apiResponse.ResponseCode = (int)response.StatusCode;  
  8.   
  9.             //TripModel dataToReturnFormat = new TripModel();  
  10.             //var format = JsonConvert.SerializeObject(dataToReturnFormat);  
  11.   
  12.             var data = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result).ToString().TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' }); ;  
  13.            
  14.             using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(data)))  
  15.             {  
  16.                 // Deserialization from JSON    
  17.                 DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(List<WrapperTripModel>));  
  18.                 List<WrapperTripModel> bsObj2 = (List<WrapperTripModel>)deserializer.ReadObject(ms);    
  19.             }  
 And my array of json is 
 
       {\"ID\":\"139a0d0d-5b2d-4ca3-aeeb-01557ab661c1\",\"Customer\":\"79d3005a-df77-4d29-a801-df7402347c85\",\"Asset_ID\":null,\"Asset_Name\":null,\"Asset_Type\":null,\"Trip_Type\":\"active\",\"Date_Start\":\"2019-01-15T07:09:45\",\"Date_End\":\"2019-01-15T07:09:45\",\"Address\":null,\"Start_Longitude\":\"74.393348055555555555555555556\",\"Start_Address\":\"St 77 Sec K, Lahore, Pakistan\",\"End_Longitude\":\"74.394553055555555555555555556\",\"End_Address\":\"Street 10, Lahore, Pakistan\",\"Start_Latitude\":\"31.479496388888888888888888889\",\"End_Latitude\":\"31.466073055555555555555555556\",\"Maximum_Speed\":\"37\",\"Drive_Time\":\"468\",\"Idle_Time\":\"750\",\"Distance_Traveled\":\"3.05702232557921\",\"Rating_Score\":\"100\",\"Telemetry_Records\":\"48\",\"Column\":\"priority,ignition,motion_start,digital_01,output_01,power_voltage,gps_speed,gsm_cell,gsm_lac,battery_voltage,battery_current,analog_01,unknown_013,odo_diff,odometer,unknown_012,analog_03,unknown_238,unknown_014,rsq,hours_00_counter,idle_counter,\",\"ProcessedToCRM\":true,\"CreatedOn\":\"2019-01-15T07:31:51.35\",\"assetTags\":\"0000020\"},

Brought to you by:

Answers (4)