如何将空对象 c# 序列化为 JSON

How serialize null object c# to JSON

我有一个带有符号的对象:

public class CompanyTeam
{
    public string companyGuid { get; set; }
    public string companyId { get; set; }
}

public class Team
{
    public string teamGuid { get; set; }
    public string teamName { get; set; }
    public CompanyTeam company { get; set; }
}

Team 对象有除 CompanyTeam 之外的数据。序列化我的对象时

json = new JavaScriptSerializer().Serialize(teamObject);

return

{
    "teamGuid": "GUIDdata",
    "teamName": "nameData",
    "company": null,
}

我尝试实例化 CompanyTeam 对象,但 return 对象具有空数据:

{
    "teamGuid": "GUIDdata",
    "teamName": "nameData",
    "company": {
                  "companyGuid" : null,
                  "companyId" : null
               },
}

你是怎么得到这个结果的?有什么想法吗?

{
    "teamGuid": "GUIDdata",
    "teamName": "nameData",
    "company": {},
}

您可以尝试以下方法来实现您想要的并继续使用 JavaScriptSerializer:

public class Team
{
    public Team()
    {
        teamGuid = "I have a value!";
        teamName = "me too!";
    }

    public Team(CompanyTeam company) : this()
    {
        this.company = company;
    }
    public string teamGuid { get; set; }
    public string teamName { get; set; }
    public CompanyTeam company { get; set; }

    public dynamic GetSerializeInfo() => new
    {
        teamGuid,
        teamName,
        company = company ?? new object()
    };
}

还有你的公司class

  public class CompanyTeam
    {
        public CompanyTeam()
        {
            companyGuid = "someGuid";
            companyId = "someId";
        }
        public string companyGuid { get; set; }
        public string companyId { get; set; }
    }

您可以编写一个方法 returning 动态,如果它不为 null 或新对象,您可以在其中 return 公司。测试:

static void Main(string[] args)
        {
            var teamObj = new Team();
            var json = new JavaScriptSerializer().Serialize(teamObj.GetSerializeInfo());
            Console.WriteLine(json);
            Console.ReadLine();
        }

并且输出:

{"teamGuid":"I have a value!","teamName":"me too!","company":{}}

如果您使用提供非空公司的构造函数,那么您将得到:

{"teamGuid":"I have a value!","teamName":"me too!","company":{"companyGuid":"someGuid","companyId":"someId"}}

希望对您有所帮助!