简体   繁体   中英

How serialize null object c# to JSON

I have an object with notation:

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

The Team object have data except CompanyTeam. When serialize my object

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

return

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

I try instance the CompanyTeam Object but return object with null data:

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

How could you get this result? any ideas?

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

You may try the following in order to achieve what you want and to keep using 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()
    };
}

And your company class

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

You can write a method returning a dynamic where you can either return company if it is not null or a new object. Testing:

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

And the output:

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

If you use the constructur providing a not null company then you get:

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM