如何在C#中从HttpWebResponse获取数据并处理指定JSON格式响应?
Great question! Parsing and processing JSON responses from HttpWebResponse in C# is totally manageable with the right approach. Let's walk through the process step by step:
Step 1: Extract the JSON string from the response
First, you need to read the response stream and convert it into a string. Always use using statements to ensure resources are properly disposed:
// Assuming you already have your HttpWebResponse object (named response) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { string jsonResponse = reader.ReadToEnd(); // Now you have the full JSON string to work with }
Important: Don't forget to check if the response was successful first (e.g., response.StatusCode == HttpStatusCode.OK) to avoid parsing errors from error responses.
Step 2: Deserialize JSON into C# objects (Recommended)
The cleanest way to work with the data is to deserialize it into strongly-typed C# classes. This gives you intellisense and type safety.
First, define your model classes
Match the structure of your JSON (add all properties you need from the response):
// Root response object public class IncidentRoot { [JsonPropertyName("result")] // For System.Text.Json // OR [JsonProperty("result")] for Newtonsoft.Json public List<Incident> Result { get; set; } } public class Incident { [JsonPropertyName("parent")] public string Parent { get; set; } [JsonPropertyName("made_sla")] public bool MadeSla { get; set; } [JsonPropertyName("sys_updated_on")] public DateTime SysUpdatedOn { get; set; } [JsonPropertyName("number")] public string Number { get; set; } [JsonPropertyName("opened_by")] public OpenedBy OpenedBy { get; set; } // Add other properties like caused_by, watch_list, sys_updated_by as needed } public class OpenedBy { [JsonPropertyName("link")] public string Link { get; set; } [JsonPropertyName("value")] public string Value { get; set; } }
Option 1: Using System.Text.Json (Built-in for .NET Core 3.0+, .NET 5+)
If you're using a modern .NET version, use the built-in serializer:
using System.Text.Json; // Inside the using block where you got jsonResponse var incidentRoot = JsonSerializer.Deserialize<IncidentRoot>(jsonResponse); // Access the first incident in the result list if (incidentRoot?.Result?.Count > 0) { var firstIncident = incidentRoot.Result[0]; Console.WriteLine($"Incident Number: {firstIncident.Number}"); Console.WriteLine($"Opened By User ID: {firstIncident.OpenedBy.Value}"); }
Option 2: Using Newtonsoft.Json (Json.NET, popular for older .NET Framework)
If you're working with .NET Framework, install the Newtonsoft.Json NuGet package first, then use:
using Newtonsoft.Json; // Inside the using block var incidentRoot = JsonConvert.DeserializeObject<IncidentRoot>(jsonResponse); if (incidentRoot?.Result?.Any() == true) { var firstIncident = incidentRoot.Result.First(); Console.WriteLine($"Incident Number: {firstIncident.Number}"); Console.WriteLine($"Opened By Link: {firstIncident.OpenedBy.Link}"); }
Step 3: Alternative - Parse JSON dynamically (No classes needed)
If you don't want to create model classes (not recommended for production code due to lack of type safety), you can parse the JSON dynamically:
With Newtonsoft.Json:
var jsonObj = JObject.Parse(jsonResponse); var firstIncident = jsonObj["result"][0]; string incidentNumber = (string)firstIncident["number"]; string openedByValue = (string)firstIncident["opened_by"]["value"];
With System.Text.Json:
using (JsonDocument doc = JsonDocument.Parse(jsonResponse)) { JsonElement root = doc.RootElement; JsonElement resultArray = root.GetProperty("result"); JsonElement firstIncident = resultArray[0]; string incidentNumber = firstIncident.GetProperty("number").GetString(); string openedByValue = firstIncident.GetProperty("opened_by").GetProperty("value").GetString(); }
Key Notes
- Always handle exceptions (e.g.,
JsonExceptionfor parsing errors,IOExceptionfor stream issues) to make your code robust. - For large responses, consider streaming the deserialization instead of reading the entire string into memory (both libraries support this).
- Make sure the property names in your model classes match the JSON keys (use the attribute mappings if you prefer different C# naming conventions).
内容的提问来源于stack exchange,提问作者pratha1995

