如何将指定JSON字符串正确转换为.NET对象?
Fixing JSON to .NET Object Conversion Issues
Let’s walk through the problems in your original code and fix them step by step:
Key Issues in Your Current Code
- Mismatched JSON Structure: Your JSON is a single top-level object (not a list) containing
warnings,errors, andstatusproperties. But you’re trying to deserialize it into aList<Status>, which will fail because the JSON isn’t an array. - Incorrect Class Definition: Your
Statusclass doesn’t mirror the JSON structure. The JSON has nested arrays of warning/error objects (each withcodeandmessage), plus a top-levelstatusstring—your class doesn’t account for any of this. - Logical Error: Your loop tries to access
status.code, but yourStatusclass only has astatusproperty (and nocode), which would cause a compile error.
Step 1: Define Correct Class Structures
First, create classes that exactly match the JSON’s hierarchy:
// Represents individual warning/error entries in the JSON public class MessageEntry { public int code { get; set; } public string message { get; set; } } // Represents the entire root JSON object public class ApiResponse { public List<MessageEntry> warnings { get; set; } public List<MessageEntry> errors { get; set; } public string status { get; set; } }
Step 2: Correct Deserialization Code
Now adjust your code to deserialize to the proper class. Below are two approaches—one using the legacy JavaScriptSerializer, and a modern alternative recommended for newer .NET versions.
Option 1: Using JavaScriptSerializer (Legacy .NET Framework)
string sample = "{\"warnings\":[{\"code\":3,\"message\":\"Invalid number\"}],\"errors\":[{\"code\":4,\"message\":\"No recipients specified\"}],\"status\":\"failure\"}"; JavaScriptSerializer js = new JavaScriptSerializer(); ApiResponse response = js.Deserialize<ApiResponse>(sample); // Target the root class // Example: Access the deserialized data string responseStatus = response.status; // Will return "failure" foreach (var warning in response.warnings) { Console.WriteLine($"Warning: Code {warning.code} - {warning.message}"); } foreach (var error in response.errors) { Console.WriteLine($"Error: Code {error.code} - {error.message}"); } Response.Write(responseStatus); // Write the actual status instead of hardcoding "success"
Option 2: Using System.Text.Json (Modern .NET Core/.NET 5+)
For newer .NET versions, use the built-in System.Text.Json library (no external dependencies needed):
using System.Text.Json; string sample = "{\"warnings\":[{\"code\":3,\"message\":\"Invalid number\"}],\"errors\":[{\"code\":4,\"message\":\"No recipients specified\"}],\"status\":\"failure\"}"; ApiResponse response = JsonSerializer.Deserialize<ApiResponse>(sample); // Access data the same way as the legacy example string responseStatus = response.status; // ... iterate over warnings/errors as needed
Key Fixes Explained
- Class Alignment: The
ApiResponseclass maps directly to the top-level JSON properties, whileMessageEntryhandles each nested warning/error object. - Correct Deserialization Target: We deserialize to a single
ApiResponseobject (matching the JSON’s structure) instead of a list. - Valid Data Access: You can now properly retrieve the
statusstring and iterate over warnings/errors to access their codes and messages.
Bonus: Newtonsoft.Json (Json.NET) Alternative
If you prefer using Newtonsoft.Json (a popular third-party library), install the NuGet package and use this code:
using Newtonsoft.Json; ApiResponse response = JsonConvert.DeserializeObject<ApiResponse>(sample);
内容的提问来源于stack exchange,提问作者Venkatesh
相关产品推荐
相关产品推荐

