有没有一种方法可以将C#类转换为JSON字符串

时间:2020-08-11 09:50:21

标签: 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字符串,因此想知道,而不是手动进行操作,如果我们有任何可以使用的在线工具?

2 个答案:

答案 0 :(得分:4)

您可以考虑使用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);

答案 1 :(得分:0)

您可以尝试以下链接:https://csharp2json.io/

,并且在尝试转换JSON之前,请分配所有类成员的值。 该示例已经在此网络上给出