如何在C#或Python中解析Contextual Web Search API返回的JSON响应?
Got it, let's break down how to parse the JSON response from the Contextual Web Search API in both C# and Python. I'll share practical, runnable code examples so you can implement this quickly.
C# Implementation
C# is a statically typed language, so we'll start by defining data models that match the API's JSON structure, then deserialize the response into those models.
Step 1: Send the API Request
First, use HttpClient to fetch the JSON response (make sure to replace your API key and search parameters as needed):
using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { var apiKey = "YOUR_API_KEY"; var searchQuery = "your search term"; using var client = new HttpClient(); var response = await client.GetAsync($"https://contextualwebsearch.com/api/Search/WebSearchAPI?q={searchQuery}&key={apiKey}"); response.EnsureSuccessStatusCode(); // Throw if request fails var jsonResponse = await response.Content.ReadAsStringAsync(); // Now parse jsonResponse } }
Step 2: Define Data Models
Map the API's JSON structure to C# classes. Here's a simplified model for the core response fields (expand based on the full fields you need):
using System.Collections.Generic; public class WebSearchResponse { public int TotalCount { get; set; } public List<SearchResult> Value { get; set; } } public class SearchResult { public string Title { get; set; } public string Url { get; set; } public string Body { get; set; } public string DatePublished { get; set; } }
Step 3: Deserialize the JSON
Use either System.Text.Json (built into .NET Core 3.0+) or Newtonsoft.Json (Json.NET) to deserialize the string into your models:
Using System.Text.Json:
using System.Text.Json; var searchResults = JsonSerializer.Deserialize<WebSearchResponse>(jsonResponse); if (searchResults != null && searchResults.Value != null) { foreach (var result in searchResults.Value) { Console.WriteLine($"Title: {result.Title}"); Console.WriteLine($"URL: {result.Url}"); Console.WriteLine($"Summary: {result.Body}\n"); } }
Using Newtonsoft.Json:
If you prefer Json.NET, install the NuGet package Newtonsoft.Json first, then:
using Newtonsoft.Json; var searchResults = JsonConvert.DeserializeObject<WebSearchResponse>(jsonResponse); // Iterate through results the same way as above
Python Implementation
Python's dynamic typing makes parsing JSON simpler—no need to define classes upfront. We'll use the requests library to handle the API call and built-in JSON parsing.
Step 1: Install Dependencies (if needed)
If you don't have requests installed, run:
pip install requests
Step 2: Fetch and Parse the Response
Here's the full code to send the request, parse the JSON, and iterate through results:
import requests api_key = "YOUR_API_KEY" search_query = "your search term" url = f"https://contextualwebsearch.com/api/Search/WebSearchAPI?q={searchQuery}&key={api_key}" response = requests.get(url) response.raise_for_status() # Raise exception if request fails # Parse JSON into a Python dictionary data = response.json() # Access the search results total_results = data.get("totalCount", 0) print(f"Total results found: {total_results}\n") search_results = data.get("value", []) for result in search_results: print(f"Title: {result.get('title')}") print(f"URL: {result.get('url')}") print(f"Summary: {result.get('body')}\n")
Notes for Python
- Use
.get()to safely access fields that might be missing in the response (avoids KeyError). - The API's JSON structure may include additional fields like
imageUrl,isSafe, etc.—you can access those the same way astitleorurl.
内容的提问来源于stack exchange,提问作者Roi Krakovski

