c# - 如何在.NET中将C#对象转换为JSON字符串?

我有这样的课程:

class MyDate
{
    int year, month, day;
}

class Lad
{
    string firstName;
    string lastName;
    MyDate dateOfBirth;
}

我想把一个Lad对象转换成一个json字符串,如下所示:
{
    "firstName":"Markoff",
    "lastName":"Chaney",
    "dateOfBirth":
    {
        "year":"1901",
        "month":"4",
        "day":"30"
    }
}

(不带格式)。我找到了this link,但它使用的命名空间不在.NET 4中。我也听说过JSON.NET,但他们的网站目前似乎已关闭,我不喜欢使用外部dll文件。除了手动创建JSON字符串编写器之外,还有其他选项吗?


最佳答案:

您可以使用JavaScriptSerializer类(添加对System.Web.Extensions的引用):

using System.Web.Script.Serialization;

var json = new JavaScriptSerializer().Serialize(obj);

一个完整的例子:
using System;
using System.Web.Script.Serialization;

public class MyDate
{
    public int year;
    public int month;
    public int day;
}

public class Lad
{
    public string firstName;
    public string lastName;
    public MyDate dateOfBirth;
}

class Program
{
    static void Main()
    {
        var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
    }
}

评论