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

如何使用Newtonsoft.JSON和C#遍历嵌套JSON并生成指定字典(不使用dynamic)

如何用Newtonsoft.Json在C#中读取带数字键的tileproperties并生成字典(不使用dynamic)

我来帮你解决这个问题!要在C#里用Newtonsoft.Json读取这种带数字键的tileproperties字段并生成目标字典,而且不用dynamic关键字,咱们可以用强类型序列化的方式来实现,步骤很清晰:

首先先明确一下咱们要处理的JSON结构大概是这样的(示例):

{
  "tileproperties": {
    "0": { "TileType": "river01" },
    "1": { "TileType": "river02" },
    "19": { "TileType": "grass01" },
    "25": { "TileType": "mountain01" }
  }
}

第一步:创建对应的强类型实体类

因为不能用dynamic,咱们需要定义和JSON结构匹配的类,让Newtonsoft.Json可以精准反序列化:

using Newtonsoft.Json;

// 单个Tile的属性类,对应JSON里每个数字键下的对象
public class TileProperty
{
    // 用JsonProperty特性确保和JSON字段名完全匹配
    [JsonProperty("TileType")]
    public string TileType { get; set; }
}

// JSON根类,包含整个tileproperties字段
public class TilePropertiesRoot
{
    [JsonProperty("tileproperties")]
    // 这里用string作为字典键,因为JSON里的数字键会被序列化为字符串,后续再转成int更稳妥
    public Dictionary<string, TileProperty> TileProperties { get; set; }
}

第二步:读取JSON并转换为目标字典

接下来编写读取文件、反序列化并转换为Dictionary<int, string>的代码:

using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;

public class TileDataHandler
{
    public Dictionary<int, string> GetTileTypeDictionary(string jsonFilePath)
    {
        // 读取JSON文件内容
        string jsonContent = File.ReadAllText(jsonFilePath);
        
        // 反序列化为强类型的根对象
        var tileRoot = JsonConvert.DeserializeObject<TilePropertiesRoot>(jsonContent);
        
        // 转换为我们需要的int键、TileType值的字典
        var tileTypeDict = new Dictionary<int, string>();
        foreach (var kvp in tileRoot.TileProperties)
        {
            // 安全转换字符串键为int,避免无效键导致异常
            if (int.TryParse(kvp.Key, out int tileId))
            {
                tileTypeDict[tileId] = kvp.Value.TileType;
            }
            // 可选:如果遇到非数字键,可以在这里加日志或者跳过处理
            // else { /* 比如 Console.WriteLine($"无效的tile ID:{kvp.Key}"); */ }
        }
        
        return tileTypeDict;
    }
}

关键细节说明

  • 为什么用Dictionary<string, TileProperty>?因为JSON中的数字键在序列化时会被处理为字符串类型,用string作为键可以兼容所有合法的数字键,之后用int.TryParse转换能避免格式错误导致的崩溃,让代码更健壮。
  • 如果你的JSON里的数字键绝对保证是有效的整数,也可以直接把根类里的字典改成Dictionary<int, TileProperty>,Newtonsoft.Json会自动完成字符串到int的转换,但我还是更推荐用TryParse的方式,容错性更好。
  • 别忘了先通过NuGet安装Newtonsoft.Json包:可以在NuGet包管理器里搜索安装,或者用命令行执行 Install-Package Newtonsoft.Json。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:25:48