Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ASP.NET中获取Json值并在数据集上填充_C#_Asp.net_Json - Fatal编程技术网

C# 如何在ASP.NET中获取Json值并在数据集上填充

C# 如何在ASP.NET中获取Json值并在数据集上填充,c#,asp.net,json,C#,Asp.net,Json,我正在尝试获取JSON值,但未能检索值并填充DataSet并将其绑定到GridView上,我获取的值为空 在这里,我尝试了以下代码: var outputValue = cpmu.getCPMUdata(AgreementNo, AgreementedBy, YearOfAgreement); var serializer = new JavaScriptSerializer(); dynamic obj = serializer.Deserialize<dynamic>(outpu

我正在尝试获取JSON值,但未能检索值并填充
DataSet
并将其绑定到
GridView
上,我获取的值为空

在这里,我尝试了以下代码:

var outputValue = cpmu.getCPMUdata(AgreementNo, AgreementedBy, YearOfAgreement);
var serializer = new JavaScriptSerializer();
dynamic obj = serializer.Deserialize<dynamic>(outputValue);

var data = obj["data"];

StringReader theReader = new StringReader(data);
DataSet theDataSet = new DataSet();
theDataSet.ReadXml(theReader);

var result = theDataSet.Tables[0];

Label3.Text = theDataSet.Tables[0].Rows[0].Field<string>("AgreementNo");                                   
Label2.Text = theDataSet.Tables[0].Rows[0].Field<string>("Agreementby");
Label4.Text = theDataSet.Tables[0].Rows[0].Field<string>("YearofAgreement");

GridView2.DataSource = theDataSet;
GridView2.DataMember = theDataSet.Tables["Bill"].ToString();
GridView2.DataBind();
在variable
returnvalue
中,我得到了这样的错误类型:

{“msg”:“error”,“data”:“NA” 娜娜 \t\t未找到数据\t\t
\t\t“}


您的JSON结构可能会有所帮助。如前所述,请显示JSON结构。我们需要知道输入是什么样子的。从数据库中获取协议号、协议日期和协议年份的值,并将它们传递到JSON对象中,然后对它们进行序列化和反序列化。从头到尾,每一行都正常工作,但在“StreamReader reader1=新StreamReader(dataStream1)”的末尾;returnvalue=reader1.ReadToEnd();“它没有返回任何值并显示如下所示的消息:{“msg”:“error”,“data”:“NA-NA-NA\t\t未找到数据\t\t\t”},因此您没有得到空值,您正在从远程服务器获得有效响应。它只是一个响应,告诉您服务器没有找到要返回的实际数据。这与响应本身为NULL不同。顺便说一句,远程服务似乎在JSON中包装XML…这太奇怪了。选择一种格式并使用它。将两者混为一谈既奇怪又毫无意义。您必须反序列化JSON,然后还要反序列化其中的XML。如果每件事都是这样或那样,那就简单多了。
public string getCPMUdata(string AgreementNo, string Agreementby, string YearofAgreement)
{
    //Code to accept the SSL server certificate
    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

    //Configuration Values
    string strbaseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"];
    string strLoginBaseUrl = System.Configuration.ConfigurationManager.AppSettings["LoginBaseUrl"];
    String username = System.Configuration.ConfigurationManager.AppSettings["UserName"];
    string password = System.Configuration.ConfigurationManager.AppSettings["Password"];
    //***************

    /* Input Values */
    string strAgreementNo = AgreementNo;
    string strAgreementby = Agreementby;
    string strYearofAgreement = YearofAgreement;
    /****************/

    // Initialize the response
    string returnvalue = string.Empty;
    HttpWebResponse response = null;
    HttpWebRequest request = null;
    String responseText = null;
    String authorization;

    try
    {
        //Create the Request Url
        String requestUrl = strLoginBaseUrl + "?service=" + HttpUtility.UrlEncodeUnicode(strbaseUrl + "/3DSpace/resources/CHiPSCPMSBillDetailsModeler/CHiPSCPMSBillDetails?AgreementNo=" + HttpUtility.UrlEncode(strAgreementNo) + "&Agreementby=" + HttpUtility.UrlEncode(strAgreementby) + "&YearofAgreement=" + HttpUtility.UrlEncode(strYearofAgreement));

        request = WebRequest.Create(requestUrl) as HttpWebRequest;
        request.Method = "GET";
        request.ContentType = "application/json";
        authorization = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
        request.Headers.Add("Authorization", "Basic " + authorization);
        response = request.GetResponse() as HttpWebResponse;

        if (request.HaveResponse == true && response == null)
        {
            String msg = "response was not returned or is null";
            throw new WebException(msg);
        }

        if (response.StatusCode != HttpStatusCode.OK)
        {
            String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
            throw new WebException(msg);
        }

        // get the first HTTP response content
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        responseText = reader.ReadToEnd();

        //extract the LT code from the response string
        String lt = "";
        lt = responseText.Substring(responseText.LastIndexOf("\"lt\""));
        lt = lt.Substring(0, lt.IndexOf(","));
        lt = lt.Replace("\"lt\":", ",");
        lt = lt.Replace("\"", "");
        lt = lt.Replace("\"", "");
        lt = lt.Replace(",", "");

        //Extract Session ID from the response header
        String strJsonId = "";
        strJsonId = response.Headers["Set-Cookie"];
        strJsonId = response.Headers["Set-Cookie"].Substring(strJsonId.LastIndexOf("JSESSIONID"));
        strJsonId = strJsonId.Substring(0, strJsonId.IndexOf(";"));
        strJsonId = strJsonId.Replace("JSESSIONID", "");
        strJsonId = strJsonId.Replace("=", "");
        strJsonId = strJsonId.Trim();

        //throw exception if access token or sessionid is not available
        if (lt == "" && strJsonId == "")
        {
            String msg = "Unable to retrieve Access Token and session Key";
            throw new WebException(msg);
        }

        //Second HTTP Request to get the Data based on the 'lt' token, 'SessionID' and Query String parameters
        WebRequest requestLast = WebRequest.Create(requestUrl);
        requestLast.Headers.Add("Cookie", "JSESSIONID=" + strJsonId);
        requestLast.Method = "POST";
        string postData = "lt=" + lt + "&username=" + username + "&password=" + password;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Set the ContentType property of the WebRequest.
        requestLast.ContentType = "application/x-www-form-urlencoded";
        requestLast.ContentLength = byteArray.Length;

        // Get the request stream.
        Stream dataStream1 = requestLast.GetRequestStream();
        dataStream1.Write(byteArray, 0, byteArray.Length);
        dataStream1.Close();

        // Get the response.
        WebResponse responseLast = requestLast.GetResponse();
        dataStream1 = responseLast.GetResponseStream();
        StreamReader reader1 = new StreamReader(dataStream1);
        returnvalue = reader1.ReadToEnd();

        // Clean up the streams.
        reader.Close();
        reader1.Close();
        dataStream1.Close();
        response.Close();
        responseLast.Close();

    }
    catch (WebException e)
    {
        if (e.Response != null)
        {
            response = (HttpWebResponse)e.Response;
            returnvalue = response.StatusCode + " " + response.StatusDescription;
        }
        else
        {
            returnvalue = e.Message;
        }
    }
    finally
    {
        if (response != null)
        {
            response.Close();
        }
    }
    return returnvalue;
}

     public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
     {
         return true;
     }
}