消息错误:System.InvalidCastException:指定的强制转换无效10

时间:2016-08-22 10:40:59

标签: c# mysql xamarin

我的以下代码是对我的MYSql数据库的简单HTTP请求

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Json;
using System.Net;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Microsoft.CSharp;

namespace API_Test
{
[Activity(Label = "API_Test", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{

    private Button button;
    private EditText reponseAPI;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main); 

        // Get the latitude/longitude EditBox and button resources:
        button = FindViewById<Button>(Resource.Id.btnCall);

        // When the user clicks the button ...
        button.Click += async (sender, e) => {


            string url = "http://192.168.X.XX/API_xxxx.php?xxxxxx"; 


            JsonValue json = await FetchWeatherAsync(url);
            //ParseAndDisplay (json);
        };         
    }


    private async Task<JsonValue> FetchWeatherAsync(string url)
    {
        // Create an HTTP web request using the URL:
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "GET";

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

                // Return the JSON document:
                return jsonDoc;
            }
        }
    }


    private void ParseAndDisplay(JsonValue json)
    {
        reponseAPI = FindViewById<EditText>(Resource.Id.reponseAPI);

        //dynamic Toto = JsonObject.Parse(json);
        //string lolo = Toto.id;
        //reponseAPI.Text = lolo;
        //var m = JsonConvert.DeserializeObject<dynamic>(json);
        //Console.Out.WriteLine("oooo");

        //string name = m.id;       


    }
}
}

当我尝试调试它时,弹出一个弹出窗口,显示以下消息

  

“未处理的异常:System.InvalidCastException:指定的强制转换无效。”

我正在寻找stackoverflow中的解决方案。循环答案是关于Type值的,但目前我不会尝试在C#中解析我的数据,只是为了获取我的数据。

我是VM和Xamarin的初学者所以我希望“完全例外”是以下代码。

08-22 12:03:39.569 D/Mono    ( 5472): Image addref System.Json[0x9d292980] -> System.Json.dll[0x9c62fa00]: 1
08-22 12:03:39.569 D/Mono    ( 5472): Assembly System.Json[0x9d292980] added to domain RootDomain, ref_count=1
08-22 12:03:39.569 D/Mono    ( 5472): AOT module 'System.Json.dll.so' not found: dlopen failed: library "/data/app/API_Test.API_Test-1/lib/x86/libaot-System.Json.dll.so" not found
08-22 12:03:39.570 D/Mono    ( 5472): AOT module '/Users/builder/data/lanes/3540/1cf254db/source/monodroid/builds/install/mono-x86/lib/mono/aot-cache/x86/System.Json.dll.so' not found: dlopen failed: library "/data/app/API_Test.API_Test-1/lib/x86/libaot-System.Json.dll.so" not found
08-22 12:03:39.570 D/Mono    ( 5472): Config attempting to parse: 'System.Json.dll.config'.
08-22 12:03:39.570 D/Mono    ( 5472): Config attempting to parse: '/Users/builder/data/lanes/3540/1cf254db/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Json/System.Json.config'.
08-22 12:03:39.570 D/Mono    ( 5472): Assembly Ref addref API_Test[0xad97b760] -> System.Json[0x9d292980]: 2
08-22 12:03:39.570 D/Mono    ( 5472): Assembly Ref addref System.Json[0x9d292980] -> mscorlib[0xad97b700]: 14
Loaded assembly: System.Json.dll
08-22 12:03:39.589 D/Mono    ( 5472): Assembly Ref addref API_Test[0xad97b760] -> System[0xb077ce20]: 3
08-22 12:03:39.646 D/Mono    ( 5472): Assembly Ref addref Mono.Android[0xb077cee0] -> System[0xb077ce20]: 4
08-22 12:03:39.675 D/Mono    ( 5472): DllImport searching in: '__Internal' ('(null)').
08-22 12:03:39.675 D/Mono    ( 5472): Searching for 'java_interop_jnienv_call_int_method'.
08-22 12:03:39.675 D/Mono    ( 5472): Probing 'java_interop_jnienv_call_int_method'.
08-22 12:03:39.675 D/Mono    ( 5472): Found as 'java_interop_jnienv_call_int_method'.
08-22 12:03:39.683 D/Mono    ( 5472): DllImport searching in: '__Internal' ('(null)').
08-22 12:03:39.683 D/Mono    ( 5472): Searching for 'java_interop_jnienv_get_static_field_id'.
08-22 12:03:39.683 D/Mono    ( 5472): Probing 'java_interop_jnienv_get_static_field_id'.
08-22 12:03:39.683 D/Mono    ( 5472): Found as 'java_interop_jnienv_get_static_field_id'.
08-22 12:03:39.684 D/Mono    ( 5472): DllImport searching in: '__Internal' ('(null)').
08-22 12:03:39.684 D/Mono    ( 5472): Searching for 'java_interop_jnienv_get_static_object_field'.
08-22 12:03:39.684 D/Mono    ( 5472): Probing 'java_interop_jnienv_get_static_object_field'.
08-22 12:03:39.684 D/Mono    ( 5472): Found as 'java_interop_jnienv_get_static_object_field'.
08-22 12:03:39.687 D/Mono    ( 5472): DllImport searching in: '__Internal' ('(null)').
08-22 12:03:39.687 D/Mono    ( 5472): Searching for 'java_interop_jnienv_call_nonvirtual_boolean_method_a'.
08-22 12:03:39.687 D/Mono    ( 5472): Probing 'java_interop_jnienv_call_nonvirtual_boolean_method_a'.
08-22 12:03:39.687 D/Mono    ( 5472): Found as 'java_interop_jnienv_call_nonvirtual_boolean_method_a'.
Thread started:  #2
Thread started: <Thread Pool> #3
Thread started: <Thread Pool> #4
08-22 12:03:39.772 D/Mono    ( 5472): [0x9bb7f930] worker starting
Thread started: <Thread Pool> #5
08-22 12:03:39.810 D/Mono    ( 5472): [0x9b97f930] worker starting
Thread started: <Thread Pool> #6
08-22 12:03:39.878 D/Mono    ( 5472): [0x9bb7f930] hill climbing, change max number of threads 2
08-22 12:03:39.948 D/Mono    ( 5472): Assembly Ref addref System.Json[0x9d292980] -> System.Core[0x9d2913c0]: 4
08-22 12:03:39.962 D/Mono    ( 5472): Assembly Ref addref System.Json[0x9d292980] -> System[0xb077ce20]: 5
08-22 12:03:40.011 D/Mono    ( 5472): DllImport attempting to load: '/system/lib/liblog.so'.
08-22 12:03:40.011 D/Mono    ( 5472): DllImport loaded library '/system/lib/liblog.so'.
08-22 12:03:40.011 D/Mono    ( 5472): DllImport searching in: '/system/lib/liblog.so' ('/system/lib/liblog.so').
08-22 12:03:40.011 D/Mono    ( 5472): Searching for '__android_log_print'.
08-22 12:03:40.011 D/Mono    ( 5472): Probing '__android_log_print'.
08-22 12:03:40.011 D/Mono    ( 5472): Found as '__android_log_print'.
08-22 12:03:40.011 I/mono-stdout( 5472): ducon: [{"id": "1", "nom": "Dylan", "prenom": "Bob"}]
ducon: [{"id": "1", "nom": "Dylan", "prenom": "Bob"}]
08-22 12:03:40.016 D/Mono    ( 5472): Assembly Ref addref API_Test[0xad97b760] -> Newtonsoft.Json[0xad97bd00]: 2
08-22 12:03:40.016 D/Mono    ( 5472): Assembly Ref addref Newtonsoft.Json[0xad97bd00] -> System.Runtime[0xad97bee0]: 3
Unhandled Exception:

System.InvalidCastException: Specified cast is not valid.

1 个答案:

答案 0 :(得分:0)

首先,你必须添加包:Newtonsoft.Json

private async Task<JsonValue> FetchWeatherAsync(string url)
{
  //return json string
}

创建模型,准备绑定json对象,例如

public class MyUser
{
  public int id {get;set;}
  public string name {get;set;}
}

然后,将json字符串解析为object

private void ParseAndDisplay(string JsonString)
{
 var data = JsonConvert.DeserializeObject<MyUser>(jsonString);
 var UserID = data.id; //get property value
 //.....set something TextView value
}
试试吧!