c#将json字符串转换为对象数组
在C#中,将JSON字符串转换为对象数组是一个常见的需求,特别是在处理来自Web API的响应或需要反序列化本地文件内容时。这可以通过使用Newtonsoft.Json
(也称为Json.NET)库或.NET Core内置的System.Text.Json
来完成。以下是如何使用这两种方法实现:
使用Newtonsoft.Json
首先,确保你的项目中已经安装了Newtonsoft.Json包。你可以通过NuGet包管理器安装它:
Install-Package Newtonsoft.Json
然后,你可以使用以下代码将JSON字符串转换为对象数组:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;public class MyObject
{public string Name { get; set; }public int Age { get; set; }
}class Program
{static void Main(){string json = "[{\"Name\":\"John\", \"Age\":30}, {\"Name\":\"Jane\", \"Age\":25}]";List<MyObject> objects = JsonConvert.DeserializeObject<List<MyObject>>(json);foreach (var obj in objects){Console.WriteLine($"Name: {obj.Name}, Age: {obj.Age}");}}
}
使用System.Text.Json (适用于.NET Core 3.0及以上版本)
对于.NET Core 3.0及以上版本,你可以使用System.Text.Json
,这是微软推荐的JSON处理库。首先,确保你的项目是针对.NET Core 3.0或更高版本。
using System;
using System.Collections.Generic;
using System.Text.Json;public class MyObject
{public string Name { get; set; }public int Age { get; set; }
}class Program
{static void Main(){string json = "[{\"Name\":\"John\", \"Age\":30}, {\"Name\":\"Jane\", \"Age\":25}]";List<MyObject> objects = JsonSerializer.Deserialize<List<MyObject>>(json);foreach (var obj in objects){Console.WriteLine($"Name: {obj.Name}, Age: {obj.Age}");}}
}
注意事项
-
确保你的JSON字符串格式正确,特别是数组的格式(使用方括号
[]
包围对象列表)。 -
在使用
System.Text.Json
时,如果你的对象属性名与JSON中的键不匹配,你可以使用[JsonPropertyName]
属性来指定映射。例如:[JsonPropertyName("name")] public string Name { get; set; }
。 -
对于复杂类型的对象,你可能需要为每个属性定义相应的类,就像上面的
MyObject
类示例那样。
选择哪种方法取决于你的项目需求和所使用的.NET版本。Newtonsoft.Json
提供了更多的灵活性和强大的功能,而System.Text.Json
在性能上通常更优,是微软官方推荐的方式。