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

C#使用Newtonsoft读取含对象值的JSON文件遇反序列化问题

解决Newtonsoft.Json反序列化含嵌套对象的JSON到自定义类的问题

1. 修正实体类定义

你的AnimationFrame类定义不符合JSON结构:JSON中的frame是一个包含x/y/w/h的单一对象,而非嵌套字典。需要重新定义实体类来匹配JSON结构:

// 对应JSON中的frame子对象
public class Frame
{
    public int x { get; set; }
    public int y { get; set; }
    public int w { get; set; }
    public int h { get; set; }
}

// 对应每个帧的完整数据结构
public class AnimationFrame
{
    public Frame frame { get; set; }
    public int duration { get; set; }
}

// 对应整个JSON的根对象
public class AnimationData
{
    public Dictionary<string, AnimationFrame> frames { get; set; }
}

2. 正确反序列化并访问数据

直接反序列化到强类型的AnimationData类,无需使用Dictionary<string, object>,这样可以避免类型转换的麻烦,直接通过属性访问数据:

string framesDataJson = File.ReadAllText(@"Content/simple.json");
AnimationData animationData = JsonConvert.DeserializeObject<AnimationData>(framesDataJson);

// 示例:访问第一个帧的属性
AnimationFrame firstFrame = animationData.frames["0"];
Console.WriteLine($"Frame位置:x={firstFrame.frame.x}, y={firstFrame.frame.y},时长:{firstFrame.duration}ms");

原代码报错原因

你原代码中jsonFramesData["frames"]返回的是object类型,C#不允许直接对object使用索引器["0"]。虽然可以通过强制类型转换临时解决(比如((Dictionary<string, object>)jsonFramesData["frames"])["0"]),但这种方式不仅繁琐,还容易引发类型转换异常,强类型反序列化是更可靠的方案。

内容的提问来源于stack exchange,提问作者Yohan.sb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:11:07