以json格式阅读HttpwebResponse

时间:2017-07-05 14:40:27

标签: c# json-deserialization

我怀疑如何创建一个用于接收来自HttpWebResponse的响应的类。

我用来接收json响应的代码是:

using (var response = (HttpWebResponse)request.GetResponse())
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var objText = reader.ReadToEnd();
                ResJson myojb = (ResJson )js.Deserialize(objText, typeof(ResJson ));
            }
        }

我收到的json是:

{
"name": "Rube Goldberg Machine Stage 1",
"published": true,
"description": "<p>.STEP Version\n<br /><br><a href=\"http://grabcad.com/cadfiles/rube-goldberg-experiment\">Rube Goldberg Experiment</a></p>",
"raw_description": ".STEP Version\r\nhttp://grabcad.com/cadfiles/rube-goldberg-experiment",
"cached_slug": "rube-goldberg-machine-stage-1",
"created_at": "2011-04-06T21:58:06Z",
"updated_at": "2017-05-02T07:44:08Z",
"preview_image": "https://d2t1xqejof9utc.cloudfront.net/screenshots/pics/08d3763d43243a1a5f88c89dbfb8910c/card.jpg",
"image_missing_url": "https://d2t1xqejof9utc.cloudfront.net/screenshots/pics/missing_small.png",
"likes_count": 9,
"downloads_count": 116,
"comments_count": 1,
"contentfiles_count": 3,
"top_comments_count": 1,
"video_link": "https://youtu.be/paDE3KO7eb0",
"author": {
    "name": "Scott Bruins",
    "cached_slug": "scott.bruins",
    "avatar": "https://d2t1xqejof9utc.cloudfront.net/members/avatars/320/feed.gif?1316795450"
},
"tags": [
    "machine",
    "rube",
    "goldberg",
    "crowdcad"
],
"softwares": [
    {
        "name": "Other",
        "cached_slug": "other"
    },
    {
        "name": "STL",
        "cached_slug": "stl"
    },
    {
        "name": "Rendering",
        "cached_slug": "rendering"
    }
]
}

创建 ResJson 类时,我无法弄清楚set softwares变量的类型。

应如何宣布?

1 个答案:

答案 0 :(得分:0)

public class Software
{
    [JsonProperty("name")]
    public string Name {get;set;}

    [JsonProperty("cached_slug")]
    public string CachedSlug {get;set;}
}

然后在ResJson

{
    ...
    [JsonProperty("softwares")]
    public List<Software> Softwares {get;set;}
    ...
}