我正在尝试反序列化
string strurlTest = String.Format("https://jsonplaceholder.typicode.com/posts/1/comments");
WebRequest requestObjGet = WebRequest.Create(strurlTest);
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
string strresulttest = null;
JavaScriptSerializer js = new JavaScriptSerializer();
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
test t = new JavaScriptSerializer().Deserialize<dynamic>(res.ToString());
然后我收到错误
“无效的Json基本体”
请对此提供支持。 杰森数据 https://jsonplaceholder.typicode.com/posts/1/comments
答案 0 :(得分:0)
尝试
更改此行:
test t = new JavaScriptSerializer().Deserialize<dynamic>(res.ToString());
对此:
strresulttest = sr.ReadToEnd();
test t = new JavaScriptSerializer().Deserialize<dynamic>(strresulttest);
答案 1 :(得分:0)
Test[] tests= new JavaScriptSerializer().Deserialize<Test[]>(strresulttest );
使用strresulttest而不是res。因此,您的“测试”课程应类似于
public class Test
{
public int postId { get; set; }
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string body { get; set; }
}
根据评论有效的解决方案
using System;
using System.IO;
using System.Net;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
string strurlTest = String.Format("https://jsonplaceholder.typicode.com/posts/1/comments");
WebRequest requestObjGet = WebRequest.Create(strurlTest);
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
string strresulttest = null;
JavaScriptSerializer js = new JavaScriptSerializer();
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
Test[] tests = new JavaScriptSerializer().Deserialize<Test[]>(strresulttest);
}
return View();
}
}
public class Test
{
public int postId { get; set; }
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string body { get; set; }
}
}