首页 > 解决方案 > 无效的 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

标签: c#

解决方案


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; }
    }
}

推荐阅读