如何在 C# 中读取 JSON 块



我收到来自webRequest的响应 下面是代码,

HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
{
    using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objText = reader.ReadToEnd();
        while (reader.EndOfStream)
        {
            objText = reader.ReadLine();
            MyObject myobj= (MyObject)js.Deserialize<MyObject>(objText);
        }
    }
}

我收到以下格式的 JSON 响应,我想将此 JSON 响应与 myobj 绑定。

{"Results":[{"Id":"571611","ModerationStatus":"APPROVED","LastModificationTime":
        "2011-10-31T05:36:33-05:00"
        ,"IsRatingsOnly":true,"TotalCommentCount":0,"Rating":5,"RatingRange":5,"IsRecommended":true,"TotalFeedbackCount":0,"TotalPositiveFeedbackCount":0,"TotalNegativeFeedbackCount":0,"DisplayLocale":"en_US","SubmissionTime":
        "2011-05-25T00:00:00-05:00"
        ,"IsFeatured":false,"LastModeratedTime":
        "2011-10-31T05:36:33-05:00"
        ,"ProductId":"3240234","AuthorId":"z7knrbjunvi022pe4swqp18fra"},{"Id":"571612","ModerationStatus":"APPROVED","LastModificationTime":
        "2011-10-31T05:36:33-05:00"
        ,"IsRatingsOnly":true,"TotalCommentCount":0,"Rating":5,"RatingRange":5,"IsRecommended":true,"TotalFeedbackCount":0,"TotalPositiveFeedbackCount":0,"TotalNegativeFeedbackCount":0,"DisplayLocale":"en_US","SubmissionTime":
        "2011-05-25T00:00:00-05:00"
        ,"IsFeatured":false,"LastModeratedTime":
        "2011-10-31T05:36:33-05:00"
        ,"ProductId":"3240234","AuthorId":"zsknvekklaxl56nzwliultz5mp"}],"Includes":{"Products":{"3240234":{"Id":"3240234","Name":"Rosner Chevrolet","Description":"Brevard County","BrandExternalId":"01","Brand":{"Id":"01","Name":"Personal Accounts"},"CategoryId":"324","ProductPageUrl":"https://www.sccu.com/personal/vehicle-loans/dealer-review.asp?did=234&dealerName=Rosner+Chevrolet"}},"Authors":{"z7knrbjunvi022pe4swqp18fra":{"Id":"z7knrbjunvi022pe4swqp18fra","ModerationStatus":"NONE"},"zsknvekklaxl56nzwliultz5mp":{"Id":"zsknvekklaxl56nzwliultz5mp","ModerationStatus":"NONE"}}},"HasErrors":false,"Offset":0,"Limit":2,"TotalResults":25}

我想一个接一个地读取这个 JSON 块(这个具有多个值的 JSON 块)并存储在对象列表中。

你可以这样做,首先尝试在这里解析你的 Json 字符串 \

http://json.parser.online.fr/

如果它通过那里,那么转到 http://json2csharp.com/...粘贴您的字符串...它将生成一个具有属性的类

然后

将类粘贴到代码 中。 并为该类创建新对象

并调用反序列化

   JavaScriptSerializer js = new JavaScriptSerializer();
   var Data = DeserializeFromJson<RootObject>("Json String");
 public T DeserializeFromJson<T>(string json)
    {
        System.Web.Script.Serialization.JavaScriptSerializer ObjJSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        T deserializedProduct = ObjJSerializer.Deserialize<T>(json);
        return deserializedProduct;
    }

public class Result
{
public string Id { get; set; }
public string ModerationStatus { get; set; }
public string LastModificationTime { get; set; }
public bool IsRatingsOnly { get; set; }
public int TotalCommentCount { get; set; }
public int Rating { get; set; }
public int RatingRange { get; set; }
public bool IsRecommended { get; set; }
public int TotalFeedbackCount { get; set; }
public int TotalPositiveFeedbackCount { get; set; }
public int TotalNegativeFeedbackCount { get; set; }
public string DisplayLocale { get; set; }
public string SubmissionTime { get; set; }
public bool IsFeatured { get; set; }
public string LastModeratedTime { get; set; }
public string ProductId { get; set; }
public string AuthorId { get; set; }
 }
  public class Brand
  {
public string Id { get; set; }
public string Name { get; set; }
  }
  public class __invalid_type__3240234
 {
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string BrandExternalId { get; set; }
public Brand Brand { get; set; }
public string CategoryId { get; set; }
public string ProductPageUrl { get; set; }
   }
public class Products
{
public __invalid_type__3240234 __invalid_name__3240234 { get; set; }
 }
 public class Z7knrbjunvi022pe4swqp18fra
{
public string Id { get; set; }
public string ModerationStatus { get; set; }
}
 public class Zsknvekklaxl56nzwliultz5mp
{ 
public string Id { get; set; }
public string ModerationStatus { get; set; }
}
public class Authors
{
public Z7knrbjunvi022pe4swqp18fra z7knrbjunvi022pe4swqp18fra { get; set; }
public Zsknvekklaxl56nzwliultz5mp zsknvekklaxl56nzwliultz5mp { get; set; }
 }
 public class Includes
{
public Products Products { get; set; }
public Authors Authors { get; set; }
}
public class RootObject
{
public List<Result> Results { get; set; }
public Includes Includes { get; set; }
public bool HasErrors { get; set; }
public int Offset { get; set; }
public int Limit { get; set; }
public int TotalResults { get; set; }
}

尝试:

using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
{
   using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
   {
     JavaScriptSerializer js = new JavaScriptSerializer();
     var objText = reader.ReadToEnd();  
     MyObject myobj= (MyObject)js.Deserialize<MyObject>(objText);
   }
 }

不需要 while-loop,因为您已经读取到流的末尾。只要MyObject也可以从json解析,反序列化应该没问题。

可以使用 JSON.Net 将其读入具有一行代码的 C# 对象:

static void Main(string[] args)
{
    var x = JsonConvert.DeserializeObject(JsonString);
}
private static string JsonString
{
    get
    {
        return @"{""Results"":[{""Id"":""571611"",""ModerationStatus"":""APPROVED"",""LastModificationTime"":
                ""2011-10-31T05:36:33-05:00""
                ,""IsRatingsOnly"":true,""TotalCommentCount"":0,""Rating"":5,""RatingRange"":5,""IsRecommended"":true,""TotalFeedbackCount"":0,""TotalPositiveFeedbackCount"":0,""TotalNegativeFeedbackCount"":0,""DisplayLocale"":""en_US"",""SubmissionTime"":
                ""2011-05-25T00:00:00-05:00""
                ,""IsFeatured"":false,""LastModeratedTime"":
                ""2011-10-31T05:36:33-05:00""
                ,""ProductId"":""3240234"",""AuthorId"":""z7knrbjunvi022pe4swqp18fra""},{""Id"":""571612"",""ModerationStatus"":""APPROVED"",""LastModificationTime"":
                ""2011-10-31T05:36:33-05:00""
                ,""IsRatingsOnly"":true,""TotalCommentCount"":0,""Rating"":5,""RatingRange"":5,""IsRecommended"":true,""TotalFeedbackCount"":0,""TotalPositiveFeedbackCount"":0,""TotalNegativeFeedbackCount"":0,""DisplayLocale"":""en_US"",""SubmissionTime"":
                ""2011-05-25T00:00:00-05:00""
                ,""IsFeatured"":false,""LastModeratedTime"":
                ""2011-10-31T05:36:33-05:00""
                ,""ProductId"":""3240234"",""AuthorId"":""zsknvekklaxl56nzwliultz5mp""}],""Includes"":{""Products"":{""3240234"":{""Id"":""3240234"",""Name"":""Rosner Chevrolet"",""Description"":""Brevard County"",""BrandExternalId"":""01"",""Brand"":{""Id"":""01"",""Name"":""Personal Accounts""},""CategoryId"":""324"",""ProductPageUrl"":""https://www.sccu.com/personal/vehicle-loans/dealer-review.asp?did=234&dealerName=Rosner+Chevrolet""}},""Authors"":{""z7knrbjunvi022pe4swqp18fra"":{""Id"":""z7knrbjunvi022pe4swqp18fra"",""ModerationStatus"":""NONE""},""zsknvekklaxl56nzwliultz5mp"":{""Id"":""zsknvekklaxl56nzwliultz5mp"",""ModerationStatus"":""NONE""}}},""HasErrors"":false,""Offset"":0,""Limit"":2,""TotalResults"":25}";
    }
}

该对象将是外部 JSON 对象的数组,如果 MyObject 与 JSON 结构匹配,则以下内容应该有效:

var myobj = JsonConvert.DeserializeObject<MyObject>(JsonString);

相关内容

  • 没有找到相关文章

最新更新