如何将指定JSON反序列化为C#对象?求验证格式及最优方案
JSON格式验证与C#反序列化方案
一、JSON格式验证
你提供的JSON格式完全正确,结构合法:
- 根对象包含两个键:
geometry(嵌套对象)和density(数值类型) geometry对象包含type(字符串类型)和coordinates(双精度浮点数数组),数组元素格式正确- 所有引号、逗号、括号的使用都符合JSON语法规范,无语法错误
二、C#反序列化最佳方法
下面提供两种主流的反序列化实现方案,可根据你的.NET版本和需求选择:
方案1:使用.NET内置的System.Text.Json(推荐,无需第三方依赖)
首先定义与JSON结构匹配的实体类(通过JsonPropertyName特性映射大小写差异):
using System.Text.Json.Serialization; public class Geometry { [JsonPropertyName("type")] public string Type { get; set; } [JsonPropertyName("coordinates")] public double[] Coordinates { get; set; } } public class LocationData { [JsonPropertyName("geometry")] public Geometry Geometry { get; set; } [JsonPropertyName("density")] public int Density { get; set; } }
然后执行反序列化并读取目标数据:
using System.Text.Json; // 你的JSON字符串 string json = @" { ""geometry"": { ""type"": ""Point"", ""coordinates"": [ 51.5570726284386, 25.39156280708102 ] }, ""density"": 1 }"; // 反序列化 var locationData = JsonSerializer.Deserialize<LocationData>(json); // 读取density和coordinates int density = locationData.Density; double[] coordinates = locationData.Geometry.Coordinates;
方案2:使用第三方库Newtonsoft.Json(适用于传统.NET Framework项目)
先通过NuGet安装Newtonsoft.Json包,然后定义实体类(通过JsonProperty特性映射键名):
using Newtonsoft.Json; public class Geometry { [JsonProperty("type")] public string Type { get; set; } [JsonProperty("coordinates")] public double[] Coordinates { get; set; } } public class LocationData { [JsonProperty("geometry")] public Geometry Geometry { get; set; } [JsonProperty("density")] public int Density { get; set; } }
执行反序列化并读取数据:
using Newtonsoft.Json; string json = @" { ""geometry"": { ""type"": ""Point"", ""coordinates"": [ 51.5570726284386, 25.39156280708102 ] }, ""density"": 1 }"; var locationData = JsonConvert.DeserializeObject<LocationData>(json); int density = locationData.Density; double[] coordinates = locationData.Geometry.Coordinates;
内容的提问来源于stack exchange,提问作者Muhammad Usama Alam
相关产品推荐
相关产品推荐

