reading HttpwebResponse json response, C#

后端 未结 3 777
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 10:55

In one of my apps, I am getting the response from a webrequest. The service is Restful service and will return a result similar to the JSON format below:

{
          


        
相关标签:
3条回答
  • 2020-12-25 11:40

    First you need an object

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

    Then in here

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

    I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

    JavaScriptSerializer System.Web.Script.Serialization

    0 讨论(0)
  • 2020-12-25 11:45

    I'd use RestSharp - https://github.com/restsharp/RestSharp

    Create class to deserialize to:

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

    And the code to get that object:

    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;
    

    Check out http://restsharp.org/ to get started.

    0 讨论(0)
  • 2020-12-25 11:55

    If you're getting source in Content Use the following method

    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} ");
    }
    
    0 讨论(0)
提交回复
热议问题