I'm working in ASP.Net, JsonConvert doesn't work.How can I use JsonConvert?
I have already download NewtonSoft and write this string(using Newtonsoft;) to my project.
public void FillDataGrid()
{
DataTable dt = new DataTable();
string json;
string url = "http://192.168.0.111:2903/MigraPlus.asmx/GetDataJson";
using (WebClient client = new WebClient())
{
json = client.DownloadString(url);
}
string[] json1 = json.Split('>');
string[] json2 = json1[2].Split('<');
json = json2[0];
dt = (DataTable)JsonConvert.DeserializeObject(json, typeof(DataTable));
GridView1.DataSource = dt;
GridView1.DataBind();
}
Related
I have an issue loading data in the correct format from web services.
Web Service code:
[WebMethod]
public string LoadLearrner(string id)
{
MyFunctions func = new MyFunctions();
DataSet ds;
DataSet dtsta = SQLServer.GetDsBySP("Load_Learner_ForCRM","learnerId", id.ToString());
string[] cntName = new string[dtsta.Tables[0].Rows.Count];
List<string> list = new List<string>();
int i = 0;
foreach (DataRow rdr in dtsta.Tables[0].Rows)
{
list.Add(rdr[0].ToString());
list.Add(rdr[1].ToString());
list.Add(rdr[2].ToString());
list.Add(rdr[3].ToString());
list.Add(rdr[5].ToString());
i++;
}
String[] str = list.ToArray();
string JSONString=string.Empty;
JSONString = JsonConvert.SerializeObject(str);
return JSONString;
}
Code that's used to call the above web service method is:
WebRequest request = (HttpWebRequest)WebRequest.Create("http://abc/Company/CrmLearner.asmx/LoadLearrner?id=" + item.learner_id);
request.Method = "GET";
request.ContentType = "application/text";
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
Result is:
I don't want the result like that. I want to load proper XML or JSON and store it in an object.
i have used the Newtonsoft.Json for converting data into json format.
I have write the below code:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
string JSONString = string.Empty;
JSONString = "{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}";
return JSONString;
}
So it gives me the below output:
But i want the output like :
{"mydata":[{"id":125},{"id":137},{"id":249},{"id":201},{"id":124},
{"id":173},{"id":160},{"id":153},{"id":146},{"id":168}]}
So how can i convert to it from xml to json. ?
I run your solution in a console application and I can clearly see the problem. If you avoid building json manually, the problem will go away. As I don't have database, I have added my data rows manually. Hope that will help.
using Newtonsoft.Json;
using System;
using System.Data;
namespace Test
{
class MyDataContainer
{
public DataTable mydata { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write(DataTableToJSONWithJSONNet());
Console.Read();
}
static string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
dt.Rows.Add(1);
dt.Rows.Add(2);
MyDataContainer cont = new MyDataContainer();
cont.mydata = dt;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(cont);
//to see your attempt uncomment the blow lines
//Console.Write("{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}");
//Console.WriteLine();
return JSONString;
}
}
}
Looking into your codes, you are already declared that your output is type of JSON, so on the response data it will return a JSON string.
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
And you also declared that this is a ScriptMethod. My thought is you are testing your app by running your code and accessing the url of the web service - for example http://localhost/test.asmx and clicking the invoke button on your DataTableToJSONWithJSONNet method. This approach will really display JSON result enclosed on XML format. The best way to test your own code is to invoke the web service using something like jQuery Ajax or equivalent (client scripts).
You can change your code to something like this to achieve the output you are looking for:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyResponse DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
MyResponse result = new MyResponse();
result.mydata = dt;
return result;
}
class MyResponse
{
private object _mydata;
public object mydata { get { return this._mydata; } set { this._mydata = value; } }
public MyResponse() { }
}
In my web application there is a WCF web service. In the following method
public string GetPolicyDetails(GetPolicyDetails_ML ml)
{
var strFileName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"log.xml");
DataTable dt = new DataTable();
DataSet ds = new DataSet();
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("sp_GetPolicyDetails", con) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("#policy_id", ml.policyID);
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
string json = JsonConvert.SerializeObject(dt,Formatting.Indented);
return json;
}
catch (SqlException ex)
{
return "fail";
}
finally
{
con.Close();
con.Dispose();
}
}
will return a json string inWCF Test Client. I need to access this method from my tab application. The code i used is
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
var ds = await client.GetPolicyInfoAsync(Convert.ToInt16(txtPolicyNumber.Text));
This will get the response in to the #var ds#. My question is what is the type of this var ds and how to get the Json data out of this variable ds. Thanks in advance.
how i can get a json array return from data table in asmx service menthods.
am coded like this but am not getting in array
[WebMethod(CacheDuration = 500)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public String latency(int testId)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("GetValues", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add(new SqlParameter("TestId", testId));
DataTable dt=new DataTable();
da.Fill(dt);
string[][] JaggedArray = new string[dt.Rows.Count][];
int i = 0;
foreach (DataRow rs in dt.Rows)
{
JaggedArray[i] = new string[] { rs["Time"].ToString(), rs["minlatency"].ToString() };
i = i + 1;
}
string json = JsonConvert.SerializeObject(JaggedArray);
return json;
}
my response is
{"d":"[[\"2/3/2012 11:30:14 AM\",\"10\"],[\"2/3/2012 11:30:16 AM\",\"5\"],[\"2/3/2012 11:30:18 AM\",\"7\"]]"}
You may try .NET Framework's JavaScriptSerializer :
JavaScriptSerializer serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(
new int[][]
{
new []{1,2,3},
new []{4,5,6}
}
);
Console.WriteLine(serialized);
Console.ReadLine();
Output:
[[1,2,3],[4,5,6]]
NOTE:
JavaScriptSerializer has been reported to be slower than Json.NET.
[Below is the almost full Code modified. Currently shows illegal character error when being read].
I have a C# ASP.NET application which is currently reading an XML file from the file system and then loading it into a GridView control. In the grid I can Delete rows. There is also an file upload button below the grid which upload PDF files and they show up in the grid. My code is basically a modified version of this code
The next stage of my work involves reading the XML data as String from a database field--instead of from the XML file. For that to happen, I think I can start out by just reading from the XML file, making changes in the aspx page, and the writing the 'dataset' into a database field called 'PDF_Storage'. How can I do that. Crucially, I need to be able to convert the dataset into some kind of string format for storage. Here is my code snippet.
My database is Oracle 10 but I can figure out the Update sql syntax.
SAMPLE XML FILE:
<DataSet>
<PDF>
<pdf>MyPDF1.pdf</pdf>
</PDF>
<PDF>
<pdf>MyPDF2.pdf</pdf>
</PDF>
<PDF>
<pdf>MyPDF3.pdf</pdf>
</PDF>
</DataSet>
And the corresponding code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Oracle.DataAccess.Client;
using System.Web.Configuration;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
public partial class XMLGridTest : System.Web.UI.Page
{
public static string GetConnString()
{
return WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
void binddata()
{
DataSet ds = new DataSet();
// ds.ReadXml(Server.MapPath("testxml.xml"));
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PDF_Storage FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
//## Line Below as the 'illegal characters' problem###
ds.ReadXml(reader[0].ToString(), XmlReadMode.IgnoreSchema);
gv.DataSource = ds;
gv.DataBind();
}
else
{
// Response.Write(reader.GetString(1));
// TextBox1.Text = reader.GetString(1);
}
}
// gv.DataSource = ds;//##Hard coded for XML. Works!
// gv.DataBind();
//Finally, close the connection
oracleConn.Close();
}
protected void Canceldata(object s, GridViewCancelEditEventArgs e)
{
gv.EditIndex = -1;
binddata();
}
protected void pageddata(object s, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
binddata();
}
protected void insert(object sender, EventArgs e)
{
/////////////////////////////////File Upload Code/////////////////////////////////
// Initialize variables
string sSavePath = "ParcelPDF/"; ;
if (fileupload.PostedFile == null)
{
Label1.Text = "Must Upload a PDF file!";
return;
}
HttpPostedFile myFile = fileupload.PostedFile;
int nFileLen = myFile.ContentLength;
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".pdf")
{
Label1.Text = "The file must have an extension of .pdf";
return;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".pdf";
}
// Save the stream to disk
System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
binddata();
DataSet ds = gv.DataSource as DataSet;
DataRow dr = ds.Tables[0].NewRow();
// dr[0] = pdf.Text;
dr[0] = sFilename.ToString();
ds.Tables[0].Rows.Add(dr);
ds.AcceptChanges();
string blah = "blah";
Response.Write(ds.Tables.ToString());
// ds.WriteXml(Server.MapPath("testxml.xml"));
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
// cmd.CommandText = "SELECT OBJECTID,COMMENTS FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
StringWriter SW = new StringWriter();
ds.WriteXml(SW);
cmd.Parameters.Add(":PDF_Storage", SW.ToString());
cmd.ExecuteNonQuery();
oracleConn.Close();
binddata();
}
protected void Deletedata(object s, GridViewDeleteEventArgs e)
{
binddata();
DataSet ds = gv.DataSource as DataSet;
ds.Tables[0].Rows[gv.Rows[e.RowIndex].DataItemIndex].Delete();
// ds.WriteXml(Server.MapPath("testxml.xml"));//Disabled now. Do database. Irfan. 07/09/10
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
StringWriter SW = new StringWriter();
ds.WriteXml(SW,XmlWriteMode.IgnoreSchema);
Regex regex = new Regex(#"(\r\n|\r|\n)+");
string newText = regex.Replace(SW.ToString(), "");
cmd.Parameters.Add(":PDF_Storage", newText);
cmd.ExecuteNonQuery();
oracleConn.Close();
binddata();
string blah = "blah";
}
Here is how I have done this in the past. For the insert you can basically just write the dataset's xml representation out to a string and save it directly to a field in the database. In this case I leveraged Sql Server 2008 and an XML datatype for the database field. I think the datatype in Oracle is XMLTYPE.
Insert:
public static void InsertDataSet(string key, DataSet dataSet)
{
string xml = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
dataSet.WriteXml(ms, XmlWriteMode.WriteSchema);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
xml = sr.ReadToEnd();
}
using (SqlServerConnection c = new SqlServerConnection(connectionString))
{
c.command.CommandType = CommandType.StoredProcedure;
c.command.CommandText = "some stored procedure to do the insert";
c.command.Parameters.Clear();
c.command.Parameters.Add(new SqlParameter("#key", key));
c.command.Parameters.Add(new SqlParameter("#xml", xml));
c.command.ExecuteNonQuery();
}
}
}
Getting the dataset back out of the database is as simple as reading the xml data from the database back into a TextReader and then building a new DataSet.
Get:
public static DataSet GetDataSet(string key)
{
using (SqlServerConnection c = new SqlServerConnection(connectionString))
{
c.command.CommandType = CommandType.StoredProcedure;
c.command.CommandText = "some stored procedure to get the xml";
c.command.Parameters.Clear();
c.command.Parameters.Add(new SqlParameter("#key", key));
dr = c.command.ExecuteReader();
if (dr == null)
{
return null;
}
if (dr.HasRows)
{
while (dr.Read())
{
if (dr["xml_field"] != DBNull.Value)
{
TextReader tr = new StringReader(dr["xml_field"].ToString());
result = new DataSet();
result.ReadXml(tr, XmlReadMode.ReadSchema);
}
}
}
}
return result;
}
Hope this helps.
Enjoy!