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

时间:2017-06-19 18:04:07

标签: c# json serialization javascriptserializer

我有一个带符号的对象:

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);

返回

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

我尝试使用CompanyTeam对象但返回带有空数据的对象:

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

你怎么能得到这个结果?任何想法?

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

1 个答案:

答案 0 :(得分:2)

您可以尝试以下操作以达到您想要的效果并继续使用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()
    };
}

和你的公司班级

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

您可以编写一个返回动态的方法,如果它不是null,则可以返回公司或新对象。测试:

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

输出:

{" teamGuid":"我有价值!"," teamName":"我也是!" "公司":{}}

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

{" teamGuid":"我有价值!"," teamName":"我也是!" "公司" {" companyGuid":" someGuid"" companyId":" someId"}}

希望这有帮助!