阅读HttpwebResponse json响应,C#

时间:2011-03-31 00:13:22

标签: c# json rest httpwebrequest httpwebresponse

在我的一个应用中,我收到了网络请求的回复。该服务是Restful服务,将返回类似于以下JSON格式的结果:

{
    "id" : "1lad07",
    "text" : "test",
    "url" : "http:\/\/twitpic.com\/1lacuz",
    "width" : 220,
    "height" : 84,
    "size" : 8722,
    "type" : "png",
    "timestamp" : "Wed, 05 May 2010 16:11:48 +0000",
    "user" : {
        "id" : 12345,
        "screen_name" : "twitpicuser"
    }
}   

这是我目前的代码:

    byte[] bytes = Encoding.GetEncoding(contentEncoding).GetBytes(contents.ToString());
    request.ContentLength = bytes.Length;

    using (var requestStream = request.GetRequestStream()) {

        requestStream.Write(bytes, 0, bytes.Length);

        using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

            using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {

                //What should I do here?

            }

        }

    }

我如何阅读回复?我想要网址和用户名。

3 个答案:

答案 0 :(得分:50)

首先你需要一个对象

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

然后在这里

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

我没有使用您拥有的分层对象进行测试,但这可以让您访问所需的属性。

JavaScriptSerializer System.Web.Script.Serialization

答案 1 :(得分:12)

我使用RestSharp - https://github.com/restsharp/RestSharp

创建要反序列化的类:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

获取该对象的代码:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

查看http://restsharp.org/即可开始使用。

答案 2 :(得分:0)

如果您在“内容”中获取来源 使用以下方法

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}