将Json字符串从MVC动作反序列化到c#类
本文关键字:反序列化 Json 字符串 MVC | 更新日期: 2023-09-27 18:06:15
我有一个Ajax调用(HighChartsDB图表)在一个WebForm应用程序调用一个webservice,它使用一个WebRequest
调用MVC动作在另一个应用程序返回一个JsonResult。
我设法将数据传递回ajax调用,但我得到的数据不解析为json对象,而只是一个字符串。
我的类:
public class CategoryDataViewModel
{
public string name { get; set; }
public List<int> data { get; set; }
public double pointStart { get; set; }
public int pointInterval { get { return 86400000; } }
}
highcharts调用的ajax函数:
function getBugs(mileId) {
var results;
$.ajax({
type: 'GET',
url: 'Services/WebService.svc/GetData',
contentType: "application/json; charset=utf-8",
async: false,
data: { "mileId": parseInt(mileId) },
dataType: "json",
success: function (data) {
console.log(data);
results = data;
}
});
return results;
}
最后是WebService
public class WebService : IWebService
{
public string GetData(int mileId)
{
string url = "http://localhost:63418/Home/GetWoWData?mileId=" + mileId;
WebRequest wr = WebRequest.Create(url);
using (var response= (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
return objText;
}
}
}
}
当我在ajax调用上使用console.log(data)时,我得到:
[{'"name'":'"Sedan'",'"data'":[30,30,30,30,35],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"Low'",'"data'":[800,800,800,826,1694],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"Medium'",'"data'":[180,180,180,186,317],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"High'",'"data'":[29,29,29,34,73],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"Truck'",'"data'":[6,6,6,6,13],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"SUV'",'"data'":[-172,-172,-172,-179,-239],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"Convertible'",'"data'":[0,0,0,0,-404],'"pointStart'":1307836800000,'"pointInterval'":86400000},{'"name'":'"Limo'",'"data'":[-7,-7,-7,-8,-214],'"pointStart'":1307836800000,'"pointInterval'":86400000}]
我似乎不能设法传递回一个适当的Json对象。我尝试将其转换回我的CategoryDataViewModel与此在我的webservice:
var myojb = new CategoryDataViewModel ();
using (var response = (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response .GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
}
}
return myojb;
然后我得到Type 'Test.CategoryDataViewModel' is not supported for deserialization of an array.
变化:
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
:
myojb = (List<CategoryDataViewModel> )js.Deserialize(objText, typeof(List<CategoryDataViewModel>));
,你会没事的。该数组将反序列化为列表,没有问题。
我以前见过类似的事情,我认为你可能需要将myObj更改为列表。
List<CategoryDataViewModel> myObjs = new List<CategoryDataViewModel>();
...
myObjs = js.Deserialize<List<CategoryDataViewModel>>(objText);