You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定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, and status properties. But you’re trying to deserialize it into a List<Status>, which will fail because the JSON isn’t an array.
  • Incorrect Class Definition: Your Status class doesn’t mirror the JSON structure. The JSON has nested arrays of warning/error objects (each with code and message), plus a top-level status string—your class doesn’t account for any of this.
  • Logical Error: Your loop tries to access status.code, but your Status class only has a status property (and no code), 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 ApiResponse class maps directly to the top-level JSON properties, while MessageEntry handles each nested warning/error object.
  • Correct Deserialization Target: We deserialize to a single ApiResponse object (matching the JSON’s structure) instead of a list.
  • Valid Data Access: You can now properly retrieve the status string 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:32:45