使用c#中的datacontract序列化程序反序列化json字符串

时间:2016-12-08 08:10:53

标签: c# json serialization datacontractserializer

下面的代码用于从URL

反序列化json字符串
string s = "http://stg.api.bazaarvoice.com/data/statistics.json?apiversion=5.4&passkey=xyx&filter=productid:test1&stats=NativeReviews";

using (WebClient wc = new WebClient())  
{
   string s1 = wc.DownloadString(s);

   byte[] byteArray = Encoding.UTF8.GetBytes(s1);
   MemoryStream stream = new MemoryStream(byteArray);

   DataContractJsonSerializer serializer =
        new DataContractJsonSerializer(typeof(BVJSONRatings));
   stream.Position = 0;

   BVJSONRatings yourObject = (BVJSONRatings)serializer.ReadObject(stream);
}

这是json响应格式

{
"Errors": [], 
"HasErrors": false, 
"Includes": {}, 
"Limit": 10, 
"Locale": "en_US", 
"Offset": 0, 
"Results": [
    {
        "ProductStatistics": {
            "NativeReviewStatistics": {
                "AverageOverallRating": 5, 
                "OverallRatingRange": 5, 
                "TotalReviewCount": 1
            }, 
            "ProductId": "test3", 
            "ReviewStatistics": {
                "AverageOverallRating": 3.8333, 
                "OverallRatingRange": 5, 
                "TotalReviewCount": 6
             },
     }        
], 
"TotalResults": 1
}

我使用下面的对象将上面的json映射到它们

 public class BVJSONRatings
{
    public string ProductId;
    public string AverageOverallRating;
    public string TotalReviewCount;
    public string TotalResults;
    public IList<Results> Results { get; set; }
}

public class Results
{
    public IList<ProductStatistics> ProductStatistics { get; set; }
    public IList<string> ReviewStatistics { get; set; }
}

public class ProductStatistics
{
    public string TotalReviewCount;
    public string AverageOverallRating;
}

在反序列化的过程中,我没有得到&#34;结果&#34;我得到的只是&#34; TotalResults&#34;:1。

1 个答案:

答案 0 :(得分:2)

这是唯一与您的JSON对应的对象。您必须为每个属性使用[JsonProperty("propertyName")]

由于您的对象包含结果列表,因此Results应如下所示:IList<Results> Results { get; set; }

你的课程看起来像这样:

public RootObject()
{
    [JsonProperty("HasErrors")] //This will point to your JSON attribute 'HasErrors'
    public bool Errors { get; set; } //Note that the name is different, but it will still deserialize.

    [JsonProperty("Limit")]
    public int Limit { get; set; }

    public IList<Results> Results { get; set; }
    //Etc...
}