在ASP.NET中,可以使用JavaScriptSerializer类来将对象转换为JSON字符串,以及将JSON字符串转换为对象。以下是一个示例代码:
using System; using System.Web.Script.Serialization; public class Person { public string Name { get; set; } public int Age { get; set; } } public class JsonExample { public static void Main() { Person person = new Person { Name = "John", Age = 30 }; // 将对象转换为JSON字符串 JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonString = serializer.Serialize(person); Console.WriteLine("JSON String: " + jsonString); // 将JSON字符串转换为对象 Person deserializedPerson = serializer.Deserialize(jsonString); Console.WriteLine("Deserialized Object: " + serializer.Serialize(deserializedPerson)); } }
输出结果:
JSON String: {"Name":"John","Age":30} Deserialized Object: {"Name":"John","Age":30}
请注意,JavaScriptSerializer类在.NET Framework中可用,但在.NET Core和.NET 5及更高版本中已被弃用。在这些新版本中,可以使用System.Text.Json命名空间中的JsonSerializer类来进行JSON序列化和反序列化。以下是一个使用System.Text.Json的示例代码:
using System; using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } public class JsonExample { public static void Main() { Person person = new Person { Name = "John", Age = 30 }; // 将对象转换为JSON字符串 string jsonString = JsonSerializer.Serialize(person); Console.WriteLine("JSON String: " + jsonString); // 将JSON字符串转换为对象 Person deserializedPerson = JsonSerializer.Deserialize(jsonString); Console.WriteLine("Deserialized Object: " + JsonSerializer.Serialize(deserializedPerson)); } }
输出结果与前面的示例相同:
JSON String: {"Name":"John","Age":30} Deserialized Object: {"Name":"John","Age":30}