2017-06-19 49 views
0

我有一个对象与符号:如何序列化空对象C#来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; } 
} 

团队对象有数据除了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": {}, 
} 
+0

我对你想要的1/2方式有点失落。什么代表你期望/想要的东西? – Trey

+0

我不知道如何甚至可以用JavaScriptSerializer做到这一点,但如果您使用JSON.net(https://www.nuget.org/packages/Newtonsoft.Json/),则可以省略属性从序列化空值(http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm)。你也可以调整基本的任何东西,所以当序列化JSON时,它通常是首选项。 – ckuri

+0

@Trey我需要的序列化结果有“公司”:{},它代表JSON中的空对象 – CMedina

回答

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

你可以写返回的方法动态的,你可以返回公司,如果它不是空的或新的对象。测试:

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

和输出:

{ “teamGuid”: “我有一个价值!”, “teamName”: “我也是”, “公司”:{}}

如果使用constructur提供了一个不空公司,那么你得到:

{ “teamGuid”: “我有一个价值!”, “teamName”: “我也是!”, “公司”:{ “companyGuid”:“someGuid”,“companyId”:“someId”}}

希望这有助于!