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

如何将带数字字符串键的JSON反序列化为List<Geometry>集合?

问题描述

给定如下格式的JSON:

{"0":{"Height":190,"Left":1640,"Top":170,"Width":600},"1":{"Height":52,"Left":2250,"Top":306,"Width":112},"10":{"Height":38,"Left":2011,"Top":794,"Width":378},"100":{"Height":45,"Left":192,"Top":3318,"Width":131},"101":{"Height":42,"Left":1211,"Top":3367,"Width":1216}}

该JSON的特点:

  • 条目以数字字符串作为键,而非标准JSON数组格式
  • 条目未按数字升序排列(此点不影响需求)

已定义C#类:

public class Geometry
{
    public int Height { get; set; }
    public int Width { get; set; }
    public int Left { get; set; }
    public int Top { get; set; }
}

需求:忽略数字键,将每个键对应的内容解析为Geometry对象,最终得到List<Geometry>类型的结果。

实现方案

完全可以实现,以下是两种.NET环境下常用的实现方式:

方案一:使用Newtonsoft.Json(Json.NET)

这是.NET生态中广泛使用的第三方JSON处理库,步骤简单直接:

  1. 将JSON反序列化为Dictionary<string, Geometry>,匹配原JSON的键值对结构
  2. 提取字典中的所有值,转换为List<Geometry>

示例代码:

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

// 替换为你的实际JSON字符串
string jsonContent = "{\"0\":{\"Height\":190,\"Left\":1640,\"Top\":170,\"Width\":600},\"1\":{\"Height\":52,\"Left\":2250,\"Top\":306,\"Width\":112},\"10\":{\"Height\":38,\"Left\":2011,\"Top\":794,\"Width\":378},\"100\":{\"Height\":45,\"Left\":192,\"Top\":3318,\"Width\":131},\"101\":{\"Height\":42,\"Left\":1211,\"Top\":3367,\"Width\":1216}}";

// 反序列化为字典
var geometryDictionary = JsonConvert.DeserializeObject<Dictionary<string, Geometry>>(jsonContent);

// 提取值列表
List<Geometry> geometryList = geometryDictionary.Values.ToList();

方案二:使用System.Text.Json(.NET Core 3.0+ 内置)

如果使用.NET Core 3.0及以上版本,可直接使用框架内置的System.Text.Json库,逻辑与上述一致:

  1. 反序列化为Dictionary<string, Geometry>
  2. 将字典的值转换为列表

示例代码:

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

// 替换为你的实际JSON字符串
string jsonContent = "{\"0\":{\"Height\":190,\"Left\":1640,\"Top\":170,\"Width\":600},\"1\":{\"Height\":52,\"Left\":2250,\"Top\":306,\"Width\":112},\"10\":{\"Height\":38,\"Left\":2011,\"Top\":794,\"Width\":378},\"100\":{\"Height\":45,\"Left\":192,\"Top\":3318,\"Width\":131},\"101\":{\"Height\":42,\"Left\":1211,\"Top\":3367,\"Width\":1216}}";

// 反序列化为字典
var geometryDictionary = JsonSerializer.Deserialize<Dictionary<string, Geometry>>(jsonContent);

// 转换为List<Geometry>
List<Geometry> geometryList = geometryDictionary.Values.ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:53:26