Xamarin - 无法从源类型转换为目标类型 [英] Xamarin - Cannot cast from source type to destination type
问题描述
我想在一个动态变量反序列化一个JSON文件,但它抛出
I want to deserialize a json document in a dynamic variable, however it throws
错误:
[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
code:
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;
}
}
}
}
}
的Json如下:
<$c$c>{\"error\":false,\"id\":3,\"name\":\"***********\",\"surname\":\"*******\",\"email\":\"***********@gmail.com\",\"gsm\":\"1239102312930\",\"company\":\"\",\"address\":3}
当我尝试使用 JObject.Parse
来反序列化出现同样的错误。这是与IDE本身的问题(我使用Xamarin工作室),或者是其他什么东西?
Same error appears when I try to deserialize it using JObject.Parse
. Is this a problem with the IDE itself (I'm using Xamarin Studio) or is it something else ?
推荐答案
JsonConvert.DeserializeObject()
需要字符串
作为第一个参数。但是,您提供键入 JsonValue
的对象。我不明白为什么编译器甚至允许这一点,但是这是最有可能你的问题的根源。
JsonConvert.DeserializeObject()
takes a string
as its first parameter. However, you are supplying an object of type JsonValue
. I'm not quite sure why the compiler is even allowing this, but that's most likely the source of your problem.
只要改变
dynamic userInfo = JsonConvert.DeserializeObject(json);
到
dynamic userInfo = JsonConvert.DeserializeObject(json.ToString());
至少应该解决您的例外。这可能不是最完美的解决方案,但是。
Should at least fix your exception. This might not be the most elegant solution, however.
这篇关于Xamarin - 无法从源类型转换为目标类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!