简体   繁体   English

Invalidcastexception JsonConvert.DeserializeObject

[英]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}] 回复:[{“Height_ft”:2999.0,“Height_m”:914.0,“ID”:“c1”,“纬度”:57.588007,“经度”:-5.5233564,“名称”:“Beinn Dearg”,“湿度”: 0.81,“snowCover”:4.99,“温度”: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;
        }
    }

The json data being returned is an array of objects, not a single object, as denoted by the opening and closing brackets [] . 返回的json数据是一个对象数组,而不是单个对象,由开括号和右括号[] 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() . 要从反序列化的有效负载访问第一个山,请使用.FirstOrDefault()

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

It looks like your JSON is an Array of objects. 看起来您的JSON是一个对象数组。 You should be able to deserialize the array and get the first one like so: 您应该能够反序列化数组并获得第一个,如下所示:

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

One thing to note is that you are sort of mixing technologies here. 需要注意的一点是,你在这里混合技术。 JsonValue is from the System.Json namespace, whereas JsonConvert is from the Newtonsoft.Json (ie JSON.Net) namespace. JsonValue来自System.Json命名空间,而JsonConvert来自Newtonsoft.Json (即JSON.Net)命名空间。 If you wanted to go strictly with JSON.Net, you could do something like this: 如果你想严格遵守JSON.Net,你可以这样做:

private RootObject 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";

    using (WebResponse response = request.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader streamReader = new StreamReader(stream))
    {
        JsonSerializer serializer = new JsonSerializer();
        RootObject[] mountains = (RootObject[])serializer.Deserialize(streamReader, typeof(RootObject[]));
        return (mountains.Length > 0) ? mountains[0] : null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM