【问题标题】:Is Newtonsoft.JSON supported for .net Framework 4.6 in Xamarin.Android?Xamarin.Android 中的 .net Framework 4.6 是否支持 Newtonsoft.JSON?
【发布时间】:2017-02-13 11:30:19
【问题描述】:

我正在为一个 Android 应用程序使用基于 WCF 的 Web 服务。以前 Web 应用程序(已为其编写了 Web 服务)使用 .NET 框架 3.5,最近它迁移到了 .NET 框架 4.6。以下代码段抛出异常:

“错误:NameResolutionFailure 在 System.Net.HttpWebRequest.EndGetResponse"

url = https://121.242.223.199/SEZOnlineWebService/SezOnlineWebService.svc/FetchNumberOfSEZandUnits/1

 private async Task<JsonValue> FetchErrAsync(string url)
        {

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.ContentType = "application/json";
            request.Method = "GET";


            using (WebResponse response = await request.GetResponseAsync())
            {


                using (Stream stream = response.GetResponseStream())
                {

                    JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                                        return jsonDoc;
                }
            }
            }

网络服务已启动并正在运行。 Json 格式的数据显示在普通的网络浏览器中,但是从 android 应用程序中,我们得到了上述异常。 注意:当 Web 应用程序在 .NET 框架 3.5 上运行时,此代码运行良好

【问题讨论】:

  • 你必须通过nuget包安装它
  • 是的,我已经通过 nuget 包安装了 newtonsoft.json。
  • 确保双方的对象属性和大小写顺序相同,即您的应用和服务
  • 并在您的最后获取对象 var objectClassName = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
  • 这里的“json”是接收到的字符串响应

标签: android .net json web-services xamarin


【解决方案1】:

Xamarin.Android 中的 .net Framework 4.6 是否支持 Newtonsoft.JSON

是的,它支持 Xamarin.Android 中的 .net Framework 4.6。

您可以将流转换为字符串,然后使用Newtonsoft.JSON 将字符串转换为对象。

“错误:System.Net.HttpWebRequest.EndGetResponse 处的 NameResolutionFailure”

这个错误与Newtonsoft.JSON无关,它与网络环境有关。通过测试您的 url 。 (https://121.242.223.199/SEZOnlineWebService/SezOnlineWebService.svc/FetchNumberOfSEZandUnits/1),我发现证书存在安全问题,我认为您可以尝试使用ServerCertificateValidationCallback 绕过证书验证,然后重试。

我已经通过以下代码成功获取了你的json字符串:

 public class MainActivity : Activity
    {
        Button bt1;
        TextView tv1;
        TextView tv2;
        TextView tv3;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            bt1 = FindViewById<Button>(Resource.Id.button1);
            tv1 = FindViewById<TextView>(Resource.Id.textView1);
            tv2 = FindViewById<TextView>(Resource.Id.textView2);
            tv3 = FindViewById<TextView>(Resource.Id.textView3);
            bt1.Click += Bt1_Click;
        }

        private async void Bt1_Click(object sender, EventArgs e)
        {
            await FetchErrAsync("http://121.242.223.199/SEZOnlineWebService/SezOnlineWebService.svc/FetchNumberOfSEZandUnits/1");
        }
        public bool MyRemoteCertificateValidationCallback(System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            bool isOk = true;
            // If there are errors in the certificate chain, look at each error to determine the cause.
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                for (int i = 0; i < chain.ChainStatus.Length; i++)
                {
                    if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown)
                    {
                        chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                        chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                        chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                        chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                        bool chainIsValid = chain.Build((X509Certificate2)certificate);
                        if (!chainIsValid)
                        {
                            isOk = false;
                        }
                    }
                }
            }
            return isOk;
        }
        private async Task FetchErrAsync(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.ContentType = "application/json";
            request.Method = "GET";
            ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
            using (WebResponse response = await request.GetResponseAsync())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    //JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
                    //return jsonDoc;
                    StreamReader reader = new StreamReader(stream);
                    string text = reader.ReadToEnd();
                    tv1.Text = text;
                    var myFetchNumberOfSEZandUnitsResultguage = JsonConvert.DeserializeObject<MyFetchNumberOfSEZandUnitsResultguage>(text);
                    tv2.Text = myFetchNumberOfSEZandUnitsResultguage.FetchNumberOfSEZandUnitsResult[0].Key;
                    tv3.Text = myFetchNumberOfSEZandUnitsResultguage.FetchNumberOfSEZandUnitsResult[0].Value;
                }
            }
        }


    }
    public class MyFetchNumberOfSEZandUnitsResultguage
    {
        public List<MyKeyValue> FetchNumberOfSEZandUnitsResult { get; set; }
    }

    public class MyKeyValue
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }

屏幕截图:

【讨论】:

    【解决方案2】:

    要反序列化您对特定对象的响应,您可以使用:

    NewtonSoft.Json.JsonConvert.DeserializeObject<MyClass>(webResponseInString);
    

    还有一个重要提示:Xamarin 堆栈不完全支持 WCF,因此在使用 WCF 时要小心。

    【讨论】:

    猜你喜欢
    • 2022-12-04
    • 2018-06-04
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多