2013-05-20 66 views
0

我使用asp.net mvc4網頁API。我有由Devart實體開發產生了一些類和他們有以下結構:Asp.net MVC4的Web API XML序列化會忽略公共屬性

[Serializable] 
[XmlRoot("Test")] 
[JsonObject(MemberSerialization.OptIn)] 
public class Test 
{ 
    [XmlAttribute("property1")] 
    [JsonProperty("property1")] 
    public int Property1 
    { 
     get { return _Property1; } 
     set 
     { 
      if (_Property1 != value) 
      { 
       _Property1 = value; 
      } 
     } 
    } 
    private int _Property1; 

    [XmlAttribute("property2")] 
    [JsonProperty("property2")] 
    public int Property2 
    { 
     get { return _Property2; } 
     set 
     { 
      if (_Property2 != value) 
      { 
       _Property2 = value; 
      } 
     } 
    } 
    private int _Property2; 
} 

我有這樣的類測試控制器:

public class TestController : ApiController 
{ 
    private List<Test> _tests = new List<Test>() ; 

    public TestController() 
    { 
     _tests.Add(new Test() { Property1 = 1, Property2 = 2 }); 
     _tests.Add(new Test() { Property1 = 3, Property2 = 4 }); 
    } 

    public IEnumerable<Test> Get() 
    { 
     return _tests; 
    } 
} 

當我試圖讓JSON格式測試值就返回正確的響應:

"[{"property1":1,"property2":2},{"property1":3,"property2":4}]" 

但是當我使用XML格式將其序列不公開(Property1),但私人性質(即_Property1)和響應的樣子:

<ArrayOfTest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/TestProject.Models.Data"> 
    <Test> 
    <_Property1>1</_Property1> 
    <_Property2>2</_Property2> 
    </Test> 
    <Test> 
    <_Property1>3</_Property1> 
    <_Property2>4</_Property2> 
    </Test> 
</ArrayOfTest> 

UPD:我已經嘗試添加[非序列化]和[XmlIgnore]私人性質,但在這樣的XML輸出是空的,只是:

<ArrayOfTest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PeopleAirAPI.Models.Data"> 
    <Test/> 
    <Test/> 
</ArrayOfTest> 

的問題是如何強制XML serializator序列化公共屬性。隱藏(忽略)私有屬性不是問題。我不明白爲什麼它會序列化私有屬性,我讀過msdn文檔和其他地方:

XML序列化只能序列化公用字段和屬性。

爲什麼在這種情況下,它的行爲違背了文檔?

回答

5

的Web API使用的DataContractSerializer而不是XmlSerializer的默認情況下,它看起來在[Serializable],看着別的之前對其進行序列的所有領域。

它看起來像你的類型,設計使用XmlSerializer的序列化。我建議增加以下行:

config.Formatters.XmlFormatter.UseXmlSerializer = true; 

這將確保所有的公共屬性得到初始化,所有的XML序列化的屬性,如[XmlAttribute]得到尊重。

+0

我試圖添加類似[數據成員(NAME =「property1」)顯示串行這些屬性應該被序列化,但它沒有幫助。你的解決方案與'config.Formatters'一起工作。 – m03geek

1

試圖把[XmlIgnore]private long _Id;

+0

這是我試過的第一件事。這樣的XML輸出是空的:'' – m03geek