I have a working WCF - WPF application working, however I'm looking for some optimization.
Below is my code where a WCF restful service is exposing a JSON array, and a WPF UI is receiving it without any problem.
WCF:
public clsStatus[] GetAllStatus()
{
DataTable dt = new DataTable();
List<clsStatus> lstGetAllStatus = new List<clsStatus>();
try
{
dt = // My Data Table
foreach (DataRow dr in dt.Rows)
{
dcStatus objGetAllStatus = new clsStatus();
objGetAllStatus.Id = Convert.ToInt32(dr["Id"]);
objGetAllStatus.Status = dr["Status"].ToString();
lstGetAllStatus.Add(objGetAllStatus);
}
}
return lstGetAllStatus.ToArray();
}
In WPF UI:
public ObservableCollection<T> InvokeGet<T>(string sUrl)
{
System.Net.WebRequest request = System.Net.HttpWebRequest.Create(sUrl);
request.Method = "GET";
request.UseDefaultCredentials = true;
request.ContentLength = 0;
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
Stream objResponseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(objResponseStream);
string objResponseString = reader.ReadToEnd();
response.Close();
JavaScriptSerializer objJsonserialiser = new JavaScriptSerializer();
objJsonserialiser.MaxJsonLength = 999999999;
T[] arrResult = objJsonserialiser.Deserialize<T[]>(objResponseString);
return new ObservableCollection<T>(arrResult);
}
This way serialization/deserialization is working fine, whereas when I make the changes shown below the deserialization no longer works:
In WCF:
public string[] GetAllStatus()
{
DataTable dt = new DataTable();
try
{
dt = // My Data Table
string jsonresp = JsonConvert.SerializeObject(dt, Formatting.None);
}
return jsonresp;
}
In WPF:
public ObservableCollection<T> InvokeGet<T>(string sUrl )
{
System.Net.WebRequest request = System.Net.HttpWebRequest.Create(sUrl);
request.Method = "GET";
request.UseDefaultCredentials = true;
request.ContentLength = 0;
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
Stream objResponseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(objResponseStream);
string objResponseString = reader.ReadToEnd();
response.Close();
dsReportRequests dsrepreq = new dsReportRequests();
//This conversion is failing with error
dsrepreq = JsonConvert.DeserializeObject<dsReportRequests>(objResponseString);
}
Error: "Error converting value "[{"Id":11280,"statName}]" to type 'clsStat[]'. Path '', line 1, position 759."
I found out that the JSON format in the changed code contains escape chars (
), which seems to be causing the error while deserializing.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…