如何将C#对象转换为.NET中的JSON字符串? [英] How do I turn a C# object into a JSON string in .NET?
本文介绍了如何将C#对象转换为.NET中的JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的课程:
class MyDate
{
int year, month, day;
}
class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}
我想将Lad
对象变成这样的JSON字符串:
And I would like to turn a Lad
object into a JSON string like this:
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
(不带格式).我找到了此链接,但它使用的是不在.NET 4中的名称空间.我也听说过 JSON.NET ,但它们该站点目前似乎已关闭,并且我不希望使用外部DLL文件.除了手动创建JSON字符串编写器外,还有其他选择吗?
(without the formatting). I found this link, but it uses a namespace that's not in .NET 4. I also heard about JSON.NET, but their site seems to be down at the moment, and I'm not keen on using external DLL files. Are there other options besides manually creating a JSON string writer?
推荐答案
You could use the JavaScriptSerializer
class (add reference to 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);
}
}
这篇关于如何将C#对象转换为.NET中的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文