我有这样的课程:
class MyDate { int year, month, day; } class Lad { string firstName; string lastName; MyDate dateOfBirth; }
我想将一个Lad对象变成这样的 JSON 字符串:
Lad
{ "firstName":"Markoff", "lastName":"Chaney", "dateOfBirth": { "year":"1901", "month":"4", "day":"30" } }
(不带格式)。我找到了此链接,但是它使用了 .NET 4中 没有的命名空间。我也听说过JSON.NET,但目前他们的网站似乎已经关闭,而且我不热衷于使用外部DLL文件。
除了手动创建 JSON 字符串编写器外,还有其他选择吗?
您可以使用JavaScriptSerializer该类(添加对的引用System.Web.Extensions):
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); } }