How to fetch Json value and fill it on dataset in ASP.NET

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to fetch Json value and fill it on dataset in ASP.NET



I am trying to fetch JSON value but failed to retrieve value and fill on DataSet and bind them on GridView and I am getting null value.
here I have tried code please seen below:


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();



JSON Code:


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 reterieve 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;

}



Here in variable returnvalue, I get such type of error:


returnvalue



"msg":"error","data":" NA
</AgreementNo> NA </Agreementby> NA
</YearofAgreement> tt No Data Foundtt

</Bill>tt </xml>"





your JSON structure might help
– Ranielle Canlas
Aug 8 at 8:53





as mentioned, please show the JSON structure. We need to know what the input looks like.
– ADyson
Aug 8 at 8:59





fetch the value of agreement_no, agreement_by and year_of_agreement from database and pass them into JSON object and serialize & Deserialize them.
– vindhya
Aug 8 at 9:35





from start to end, every line works properly but at the end of " StreamReader reader1 = new StreamReader(dataStream1); returnvalue = reader1.ReadToEnd(); " it didn't return any value and show message as shown below: "msg":"error","data":" NA </AgreementNo> NA </Agreementby> NA </YearofAgreement> tt No Data Foundtt </Bill>tt </xml>"
– vindhya
Aug 8 at 9:40






so you're not getting a NULL value, you're getting a valid response from the remote server. It just happens to be a response which tells you that the server found no actual data to return. That's not the same as the response itself being NULL. Btw...the remote service appears to be wrapping XML inside JSON...that's just...weird. Choose a format and use it. Mixing the two is bizarre and bit pointless. You have to deserialise the JSON and then deserialise the XML within it as well. If everything was one or the other it would be much simpler.
– ADyson
Aug 8 at 9:56










By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered