Garrith Graham Garrith Graham - 3 months ago 38
C# Question

Invalidcastexception JsonConvert.DeserializeObject

I am getting an invalid cast exception that the specified cast is not valid. On this line:

RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1);


From the documentation this should be fine? I can see the console output is fine?


Response: [{"Height_ft": 2999.0, "Height_m": 914.0, "ID": "c1",
"Latitude": 57.588007, "Longitude": -5.5233564, "Name": "Beinn Dearg",
"humidity": 0.81, "snowCover": 4.99, "temperature": 63.0}]


Spinner spinner = (Spinner)sender;
string urlmountain = "http://removed.azurewebsites.net/api/Mountains?name=";
JsonValue json1 = FetchMountain(urlmountain+string.Format("{0}", spinner.GetItemAtPosition(e.Position)));
//below.................................
RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1); //this line
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();

private JsonValue FetchMountain(string urlmountain)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountain));
request.ContentType = "application/json";
request.Method = "GET";

// Send the request to the server and wait for the response:
using (WebResponse response = request.GetResponse())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc1 = JsonObject.Load(stream);
Console.Out.WriteLine("Response: {0}", jsonDoc1.ToString());

// Return the JSON document:
return jsonDoc1;
}
}
}
public class RootObject
{
public string ID { get; set; }

public double? Latitude { get; set; }

public double? Longitude { get; set; }

public string Name { get; set; }

public double? Height_m { get; set; }

public double? Height_ft { get; set; }

public double? temperature { get; set; }

public double? humidity { get; set; }

public double? snowCover { get; set; }

public override string ToString()
{
return Name;
}
}

Answer

The json data being returned is an array of objects, not a single object, as denoted by the opening and closing brackets []. You need to deserialize to an array or a list:

var mountains = JsonConvert.DeserializeObject<List<RootObject>>(json);

To access the first mountain from the deserialized payload, use .FirstOrDefault().

var mountain = mountains.FirstOrDefault();
if (mountain != null)
{
    string toast = mountain.Name;
    Toast.MakeText(this, toast, ToastLength.Long).Show();
}
Comments