.NET中如何将JSON字符串反序列化为对象_JSON反序列化实现方式

使用System.Text.Json或Newtonsoft.Json可将JSON字符串反序列化为对象。1. System.Text.Json是.NET Core 3.0+内置库,通过JsonSerializer.Deserialize方法实现,支持[JsonPropertyName]特性映射字段;2. Newtonsoft.Json需安装NuGet包,用JsonConvert.DeserializeObject解析,支持[JsonProperty]和[JsonIgnore]等特性;3. 对复杂结构可用JsonDocument或JObject动态解析。新项目推荐System.Text.Json,旧项目或需高级功能时选Newtonsoft.Json。

在.NET中将JSON字符串反序列化为对象,常用的方式是使用 System.Text.Json 或第三方库如 Newtonsoft.Json。以下是两种主流方式的具体实现方法。

使用 System.Text.Json(.NET Core 3.0+ 推荐)

System.Text.Json 是微软官方提供的高性能JSON处理库,内置于 .NET Core 3.0 及以上版本,无需额外安装。

基本用法如下:

using System.Text.Json;

// 定义目标类
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// JSON字符串
string jsonString = "{\"Name\":\"张三\",\"Age\":30}";

// 反序列化
Person person = JsonSerializer.Deserialize(jsonString);

注意:属性名默认需与JSON字段匹配(区分大小写),若不一致可使用 [JsonPropertyName] 特性指定映射:

public class Person
{
    [JsonPropertyName("name")]
    public string Name { get; set; }

    [JsonPropertyName("age")]
    public int Age { get; set; }
}

使用 Newtonsoft.Json(兼容性强)

Newtonsoft.Json(又称 Json.NET)是广泛使用的第三方库,功能更灵活,支持旧版.NET Framework。

需通过 NuGet 安装:Install-Package Newtonsoft.Json

使用示例:

using Newtonsoft.Json;

string jsonString = "{\"Name\":\"李四\",\"Age\":25}";
Person person = JsonConvert.DeserializeObject(jsonString);

同样支持特性控制序列化行为:

  • [JsonProperty("custom_name")] — 指定JSON字段名
  • [JsonIgnore] — 忽略该属性

处理复杂或不确定结构

当JSON结构不固定时,可反序列化为动态类型或通用容器:

  • 使用 JsonDocument(System.Text.Json)解析并访问节点
  • 使用 JObject(Newtonsoft.Json)进行动态解析

例如 Newtonsoft 中使用 JObject:

JObject jObj = JObject.Parse(jsonString);
string name = jObj["Name"]?.ToString();
基本上就这些。选择哪种方式取决于项目环境和需求:新项目推荐 System.Text.Json,追求兼容性和灵活性可用 Newtonsoft.Json。