C#中使用Google.Apis.Urlshortener遇JsonReaderException错误求助
Hey there! That JsonReaderException: Error parsing NaN value usually pops up when the API isn't returning valid JSON (maybe an error page or empty response) instead of the shortened URL data. Let's walk through the most common fixes for your code:
Common Causes & Solutions
Make sure the URL Shortener API is enabled in Google Cloud Console
This is the #1 mistake most people make. Head to your Google Cloud project, search for "URL Shortener API", and enable it. If it's not turned on, the API will return an error response that your code can't parse as valid JSON—leading directly to that NaN error.Validate your input URL
The API requires a fully qualified URL with a protocol (likehttp://orhttps://). If yoururlparameter is missing this, the API will reject it outright. Add a quick check before calling the API:public string shortenIt(string url) { // Validate the input URL has a valid protocol if (!Uri.TryCreate(url, UriKind.Absolute, out _)) { // Optionally prepend http:// if missing, or throw a clear error url = "http://" + url; // Or: throw new ArgumentException("URL must include http:// or https://"); } // Rest of your code... }Double-check your API key
Ensure your API key is copied correctly (no extra spaces or missing characters) and that it has permissions to access the URL Shortener API. You can test the key directly using Postman or curl: send a POST tohttps://www.googleapis.com/urlshortener/v1/urlwith your key as a query parameter (?key=YOUR_API_KEY) and a JSON body{"longUrl": "https://example.com"}. If this returns an error, your key or API access is the issue.Update your NuGet packages
Outdated versions ofGoogle.Apis.Urlshortenermight have compatibility issues with newer API responses. Update the package to the latest version via NuGet Package Manager to rule this out.
Revised Code with Error Handling
Here's your code with added checks and error handling to catch issues early:
using System; using Google.Apis.Services; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; public string shortenIt(string url) { // Basic input validation if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url), "URL cannot be null or empty."); // Validate URL is absolute and uses http/https if (!Uri.TryCreate(url, UriKind.Absolute, out Uri validatedUri) || (validatedUri.Scheme != Uri.UriSchemeHttp && validatedUri.Scheme != Uri.UriSchemeHttps)) { throw new ArgumentException("URL must be a valid absolute URL with http or https protocol.", nameof(url)); } try { var service = new UrlshortenerService(new BaseClientService.Initializer() { ApiKey = "YOUR_API_KEY", ApplicationName = "YOUR_APP_NAME", }); var request = service.Url.Insert(new Url { LongUrl = validatedUri.ToString() }); Url response = request.Execute(); return response.Id; } catch (Exception ex) { // Log full exception details to debug the root cause Console.WriteLine($"Error shortening URL: {ex.Message}"); Console.WriteLine($"Inner exception: {ex.InnerException?.Message}"); throw; // Re-throw to let the caller handle it, or return null/default if preferred } }
Final Notes
If you still hit the error after these steps, inspect the raw response from the API. Use a debugger breakpoint or a tool like Fiddler to see exactly what the API is returning—this will reveal if it's an error message (like "API not enabled") that the client library can't parse correctly.
内容的提问来源于stack exchange,提问作者Shomaail

