c# - 无效的 JSON 原语:System.Net.ConnectStream
问题描述
我正在尝试反序列化
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 基元”
请您的支持。Json 数据 https://jsonplaceholder.typicode.com/posts/1/comments
解决方案
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; }
}
}
推荐阅读
- javascript - 什么意味着 then() 在递归承诺中返回
- bash - 如何使用 bash 脚本输出提交次数?
- html - IE11 中的嵌套 Flexbox 中断
- java - Java Dropwizard 初始化 ConstraintValidator
- javascript - JQuery,Froala - 在光标所在的元素上更改 CSS
- arrays - VBA Array 将多个 CSV 复制到一个模板工作簿
- bash - 如何使用 bash 操作 jq 输出?
- javascript - 按唯一 ID 添加/显示每一行
- python - 我如何使用 Apache 基本上从根本上运行 python 脚本?
- visual-studio - 从自动生成输出目录停止 Visual Studio 2017