首页 > 解决方案 > 有没有办法将 c# 类转换为 JSON 字符串

问题描述

我有 C# 类,我需要将其转换为 Json 文件,我尝试寻找一些在线工具来做到这一点,但找不到

有人可以知道我们是否可以在线将其更改为 Json 字符串吗?

示例 c# 类:

public enum Culture
    {
        GB,
        US,
        IT,
        FR,
        CA,
        DE,
        SE,
        NL,
        NZ,
        AU,
        AE,
        CN,
        JP,
        IE,
        IN,
        ES
    }
    public class FullName
    {
        public string First;
        public string Last;
        public FullName(string first, string last)
        {
            this.First = first;
            this.Last = last;
        }
    }
    public class StringResourcesX
    {

        public static string HTMLAttribute_QA { get; set; }

        public static string DOB { get; set; }
    public static Dictionary<Culture, FullName> CulturalNames = new Dictionary<Culture, FullName>
    {
        {Culture.GB, new FullName(GB_Name, GB_LastName)},{Culture.US, new FullName(US_Name , US_LastName)},
        {Culture.IT, new FullName(IT_Name, IT_LastName)},{Culture.ES, new FullName(ES_Name, ES_LastName)},
        {Culture.FR, new FullName(FR_Name, FR_LastName)},{Culture.AE, new FullName(AE_Name, AE_LastName)},
        {Culture.DE, new FullName(DE_Name, DE_LastName)},{Culture.NL, new FullName(NL_Name, NL_LastName)},
        {Culture.JP, new FullName(JP_Name, JP_LastName)},{Culture.SE, new FullName(SE_Name, SE_LastName)},
        {Culture.IE, new FullName(IE_Name, IE_LastName)},{Culture.AU, new FullName(AU_Name, AU_LastName)},
        {Culture.CA, new FullName(CA_Name, CA_LastName)},{Culture.NZ, new FullName(NZ_Name, NZ_LastName)},
        {Culture.IN, new FullName(IN_Name, IN_LastName)},{Culture.CN, new FullName(CN_Name, CN_LastName)}
    };
}

我有很长的文件需要转换为 Json 字符串,所以想知道宁愿手动操作,如果我们有可以使用的在线工具吗?

标签: c#json

解决方案


您可以考虑使用 NewtonSoft 的 JsonConvert.SerializeObject 方法:

https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm

例如:

var instance = new FullName {
    First="Bob",
    Last="DaBuilda"
};

string json = JsonConvert.SerializeObject(instance, Formatting.Indented);

推荐阅读