无法从对象转换为int

本文关键字:int 转换 对象 | 更新日期: 2023-09-27 17:59:12

我以前也这样做过,但Xamarin或Android SDK中似乎发生了变化。我正在尝试用反序列化的json数据填充微调器。然而,微调器适配器不再接受我的列表了?它说我不能从object转换为int?我在这里之前遵循的教程

    Spinner spinner;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        string urlmountains = "http://my.azurewebsites.net/api/Mountains";
        JsonValue json1 = FetchMountains(urlmountains);
        var list = JsonConvert.DeserializeObject<List<RootObject>>(json1.ToString());
        spinner = FindViewById<Spinner>(Resource.Id.spinner1);
        //this line ------------------------------------------------->
        spinner.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, list); // Error here cannot convert from Object to Int?
    }

    private JsonValue FetchMountains(string urlmountains)
    {
        // Create an HTTP web request using the URL:
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountains));
        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; }
    }
}

无法从对象转换为int

您的listRootObject:的List

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

但是你的ArrayAdapter想要string:的List

spinner.Adapter = new ArrayAdapter<string>(...);

IDE无法解析适当的构造函数,因为这些类型不匹配。将ArrayAdapter的类型参数更改为RootObject:

spinner.Adapter = new ArrayAdapter<RootObject>(...);

此外,ArrayAdapter显示其模型类的ToString()方法返回的值,因此需要在RootObject类中重写该值以返回所需的string

public class RootObject
{
    ...
    public override string ToString()
    {
        return Name;
    }
}