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

如何在C#中将JSON字符串反序列化为动态对象

动态字段JSON反序列化方案

针对你提供的带动态字段的errors结构,不同编程语言都有直接的处理方式,核心是将动态字段映射到键值对类型(如字典、对象),以下是主流语言的实现:

JavaScript/TypeScript

直接用JSON.parse解析为普通对象,即可自由访问动态字段:

const jsonStr = `{"errors": {
    "StartTime, StopTime": [
      "lorem ipsum","doh rey mee far so lar ti doo","this is an error"
    ], 
    "SetupMinutes": [
      "Insufficient time until StartTime to allow for SetupMinutes",
      "Quick brown fox jumps over the lazy dog"
    ],
    "Another field with an error" : [
      "This field is bad", "this field is bad too", "all fields are bad"
    ],
    "propX":["this is another field","this is another item"],
    "propY":["this is another field","this is another item"]
}}`;

// 解析为对象
const data = JSON.parse(jsonStr);

// 访问指定动态字段
console.log(data.errors["StartTime, StopTime"]);

// 遍历所有动态字段
for (const fieldName in data.errors) {
  const errorMessages = data.errors[fieldName];
  console.log(`${fieldName}: ${errorMessages.join(', ')}`);
}

如果是TypeScript,可通过Record<string, string[]>定义类型,兼顾动态性和类型提示:

interface ErrorResponse {
  errors: Record<string, string[]>;
}

const data: ErrorResponse = JSON.parse(jsonStr);

Python

使用内置json模块解析为字典,直接操作动态字段:

import json

json_str = '''{"errors": {
    "StartTime, StopTime": [
      "lorem ipsum","doh rey mee far so lar ti doo","this is an error"
    ], 
    "SetupMinutes": [
      "Insufficient time until StartTime to allow for SetupMinutes",
      "Quick brown fox jumps over the lazy dog"
    ],
    "Another field with an error" : [
      "This field is bad", "this field is bad too", "all fields are bad"
    ],
    "propX":["this is another field","this is another item"],
    "propY":["this is another field","this is another item"]
}}'''

data = json.loads(json_str)

# 访问指定字段
print(data['errors']['StartTime, StopTime'])

# 遍历所有字段
for field_name, error_messages in data['errors'].items():
    print(f"{field_name}: {', '.join(error_messages)}")

C#

C#作为静态类型语言,有两种常用方式:

方式1:使用dynamic类型

using System;
using System.Text.Json;

string jsonStr = @"{""errors"": {
    ""StartTime, StopTime"": [
      ""lorem ipsum"",""doh rey mee far so lar ti doo"",""this is an error""
    ], 
    ""SetupMinutes"": [
      ""Insufficient time until StartTime to allow for SetupMinutes"",
      ""Quick brown fox jumps over the lazy dog""
    ],
    ""Another field with an error"" : [
      ""This field is bad"", ""this field is bad too"", ""all fields are bad""
    ],
    ""propX"":[""this is another field"",""this is another item""],
    ""propY"":[""this is another field"",""this is another item""]
}}";

dynamic data = JsonSerializer.Deserialize<dynamic>(jsonStr);

// 访问指定字段
Console.WriteLine(string.Join(", ", data.errors["StartTime, StopTime"]));

// 遍历所有字段
foreach (var kvp in data.errors)
{
    Console.WriteLine($"{kvp.Key}: {string.Join(", ", kvp.Value)}");
}

方式2:使用Dictionary<string, List<string>>强类型映射(更安全)

using System;
using System.Collections.Generic;
using System.Text.Json;

public class ErrorResponse
{
    public Dictionary<string, List<string>> Errors { get; set; }
}

string jsonStr = @"{""errors"": {
    ""StartTime, StopTime"": [
      ""lorem ipsum"",""doh rey mee far so lar ti doo"",""this is an error""
    ], 
    ""SetupMinutes"": [
      ""Insufficient time until StartTime to allow for SetupMinutes"",
      ""Quick brown fox jumps over the lazy dog""
    ],
    ""Another field with an error"" : [
      ""This field is bad"", ""this field is bad too"", ""all fields are bad""
    ],
    ""propX"":[""this is another field"",""this is another item""],
    ""propY"":[""this is another field"",""this is another item""]
}}";

ErrorResponse response = JsonSerializer.Deserialize<ErrorResponse>(jsonStr);

// 访问指定字段
Console.WriteLine(string.Join(", ", response.Errors["StartTime, StopTime"]));

// 遍历所有字段
foreach (var kvp in response.Errors)
{
    Console.WriteLine($"{kvp.Key}: {string.Join(", ", kvp.Value)}");
}

核心思路

所有方案的本质都是将动态字段映射到键值对结构(如对象、字典),这类结构天然支持不确定的键名,同时每个键对应的值统一为字符串数组,既能完整保留原始数据,又能方便地访问和遍历所有错误字段。

内容的提问来源于stack exchange,提问作者shashika nirmani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:01:38