Skip to content

C# 使用 JavaScriptSerializer 序列化及反序列化

🏷️ C#

使用 JavaScriptSerializer 首先要添加引用【System.Web.Extensions

示例代码:

csharp
using System;
using System.Web.Script.Serialization;

namespace JavaScriptSerializerSample
{
    class Program
    {
        static void Main(string args)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string jsonUser = js.Serialize(new User { Id = "user1", Name = "用户 1" });
            Console.WriteLine(jsonUser);

            //User user = js.Deserialize(jsonUser, typeof(User)) as User;
            User user = js.Deserialize<User>(jsonUser);
            Console.WriteLine(string.Format("Id:{0} Name:{1}", user.Id, user.Name));
            Console.ReadLine();
        }

        class User
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }
    }
}

输出:

js
{"Id":"user1","Name":"用户 1"}
Id:user1 Name:用户 1