我使用json.net序列化和估算我的数据表。这是成功序列化的,但是当供应序列化时,它将返回空
我的服务方法是
public string GetData()
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Name");
dt.Columns.Add("Age");
DataRow dr1 = dt.NewRow();
dr1[0] = "Name1";
dr1[1] = 20;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "Name2";
dr2[1] = 23;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "Name3";
dr3[1] = 28;
dt.Rows.Add(dr3);
return JsonConvert.SerializeObject(dt, new DataTableConverter());
}
我的网页代码如下
protected void Page_Load(object sender, EventArgs e)
{
// corrected to WebRequest from HttpWebRequest
WebRequest request = WebRequest.Create("http://ltms10/lamiservice/Service1.svc/GetData");
request.Method = "GET";
request.ContentType = "application/json; charset=utf-8";
//get response-stream, and use a streamReader to read the content
using (WebResponse response = request.GetResponse())
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
Label1.Text = jsonData;
DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonData);
grd1.DataSource = dt;
grd1.DataBind();
}
}
}
}
这里的字符串如下
返回" [{{" name ":" name1 "," age ":" 20 "},{" name ":" name2 "," age ":" 23 "},{" name ":" name3 "," age ":" 28 "}]"
尝试此
DataTable dt = (DataTable) JsonConvert.DeserializeObject(jsonData, (typeof(DataTable)));
我发现格式是问题的问题。当我使用jsontextreader阅读时,它将成功转换。因此,逃脱的角色被跳过了。我还在console.writeline()中检查了正确的数据
原始数据是
[{" name":" name1"," age":20},{" name":" name2"," age":23},{" name":" name3"," age":28}]
但是如何在jQuery中格式化。由于这个逃脱字符,图表没有绑定
更新:
我得到了我们需要通过避免逃脱字符来将数据与真正的JSON格式联系起来的灵魂。为此,我们可以使用Jsontextreader类。我不知道这是正确的方法。但这是解决此问题的工作,并获得了必不可少的数据。更改的代码在
下面使用(webresponse响应= request.getResponse()) {
using (Stream s = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
JsonTextReader reader = new JsonTextReader(new StringReader(jsonData));
string data="";
while (reader.Read())
{
if (reader.Value != null)
data += reader.Value;
}
DataTable dt = (DataTable)JsonConvert.DeserializeObject(data, typeof(DataTable));
grd1.DataSource = dt;
grd1.DataBind();
}
}
}