簡體   English   中英

Xamarin-無法從源類型轉換為目標類型

[英]Xamarin - Cannot cast from source type to destination type

我想在動態變量中反序列化json文檔,但是它拋出

一個錯誤:

[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] System.InvalidCastException: Cannot cast from source type to destination type.
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <IL 0x00011, 0x00078>
[MonoDroid] at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (object) <IL 0x00006, 0x0006b>
[MonoDroid] at Android.App.SyncContext/<Post>c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/1879/5f55a9ef/source/monodroid/src/Mono.Android/src/Android.App/SyncContext.cs:18
[MonoDroid] at Java.Lang.Thread/RunnableImplementor.Run () [0x0000b] in /Users/builder/data/lanes/1879/5f55a9ef/source/monodroid/src/Mono.Android/src/Java.Lang/Thread.cs:36
[MonoDroid] at Java.Lang.IRunnableInvoker.n_Run (intptr,intptr) [0x00009] in /Users/builder/data/lanes/1879/5f55a9ef/source/monodroid/src/Mono.Android/platforms/android-19/src/generated/Java.Lang.IRunnable.cs:71
[MonoDroid] at (wrapper dynamic-method) object.461b928a-1fde-4250-8fe8-4ab69b1f0acd (intptr,intptr) <IL 0x00011, 0x0003b>
[art] JNI RegisterNativeMethods: attempt to register 0 native methods for md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable
[AndroidRuntime] Shutting down VM   

碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Json;
using System.Net;
using System.IO;
using System.Threading.Tasks;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

using Newtonsoft.Json;

namespace HomecheckApp {
    [Activity(Label = "LoginActivity", MainLauncher = true)]
    public class LoginActivity : Activity {
        private const string apiKey = "*********************************************";
        protected override void OnCreate(Bundle bundle) {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Login);

            EditText email = FindViewById<EditText>(Resource.Id.editEmail);
            EditText password = FindViewById<EditText>(Resource.Id.editPassword);
            Button loginButton = FindViewById<Button>(Resource.Id.loginButton);
//          string url = "http://homecheck.192.168.1.102.xip.io/appapi/finduser?email" + email.Text + "&pass=" + password.Text + "&key=" + apiKey;
            loginButton.Click += async (sender, e) => {
                string url = "http://homecheck.********.eu/appapi/finduser?email=" + email.Text + "&pass=" + password.Text + "&key=" + apiKey;
                JsonValue json = await FetchUserAsync(url, apiKey);
     //This is where it breaks
                dynamic userInfo = JsonConvert.DeserializeObject(json);
    //*********
                Console.WriteLine("Email is: " + userInfo.email);
            };  
        }

        private async Task<JsonValue> FetchUserAsync(string url, string apiKey) {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.ContentType = "application/json";
            request.Method = "POST";
            using(WebResponse response = await request.GetResponseAsync()) {
                using(Stream stream = response.GetResponseStream()) {
                    JsonValue jsonResponse = await Task.Run(() => JsonObject.Load(stream));
                    Console.WriteLine(jsonResponse.ToString());
                    return jsonResponse;
                }
            }
        }
    }

}

傑森看起來像這樣:

{"error":false,"id":3,"name":"***********","surname":"*******","email":"***********@gmail.com","gsm":"1239102312930","company":"","address":3}

當我嘗試使用JObject.Parse反序列化時,會出現相同的錯誤。 這是IDE本身的問題(我正在使用Xamarin Studio)還是其他問題?

JsonConvert.DeserializeObject()string作為其第一個參數。 但是,您提供的是JsonValue類型的對象。 我不太確定為什么編譯器甚至允許這樣做,但這很可能是問題的根源。

只需更改

dynamic userInfo = JsonConvert.DeserializeObject(json);

dynamic userInfo = JsonConvert.DeserializeObject(json.ToString());

至少應該解決您的異常情況。 但是,這可能不是最優雅的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM