如何在 .NET 中将 C# 对象转换为 JSON 字符串? [英] How do I turn a C# object into a JSON string in .NET?

查看:40
本文介绍了如何在 .NET 中将 C# 对象转换为 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 文件.

(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.

除了手动创建 JSON 字符串编写器之外,还有其他选择吗?

Are there other options besides manually creating a JSON string writer?

推荐答案

请注意

Microsoft 建议您不要使用 JavaScriptSerializer

查看文档页面的标题:

对于 .NET Framework 4.7.2 及更高版本,使用 System.Text.Json 命名空间中的 API 进行序列化和反序列化.对于 .NET Framework 的早期版本,请使用 Newtonsoft.Json.

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.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);
    }
}

这篇关于如何在 .NET 中将 C# 对象转换为 JSON 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆