2010-09-01 77 views
1

我有一個REST服務,它將JSON和XML作爲輸入,並對帶有反序列化內容的外部服務執行SOAP調用。用於反序列化的類是從SOAP服務的wsdl自動生成的。我使用XmlSerializer來處理XML請求,並且我想使用Newton JSON.NET JsonSerializer for JSON。JSON.NET,XmlSerializer和「指定」屬性

現在我有問題了,WSDL生成的類包含可選atomar值(如bool,int等)的「Specified」屬性。這由XmlSerializer(根據受感染的XML設置屬性)處理,但不是由Newton JSON.NET Serializer處理。我不想強制調用者將XXXSpecified元素添加到JSON字符串中。

如何使用JSON.NET序列化程序處理「指定」屬性?

回答

0

我的解決辦法:

class MyContractResolver : DefaultContractResolver 
{ 
    private JsonObjectContract objectContract = null; 

    public override JsonContract ResolveContract(Type type) 
    { 
     JsonContract contract = base.ResolveContract(type); 
     objectContract = contract as JsonObjectContract; 
     return contract; 
    } 

    public void RemoveProperty(string name) 
    { 
     if (objectContract != null) 
     { 
      objectContract.Properties.Remove(objectContract.Properties.First(
       p => p.PropertyName == name)); 
     } 
    } 

    public void AtomarOptinalType(string name, bool specified) 
    { 
     if (objectContract != null) 
     { 
      if (!specified) 
      { 
       JsonProperty prop = objectContract.Properties.First(
        p => p.PropertyName == name); 
       objectContract.Properties.Remove(prop); 
      } 

      RemoveProperty(name + "Specified"); 
     } 
    } 
} 

,然後在生成的類的擴展名:

public partial class MyGeneratedClass 
{ 
    [OnDeserializing] 
    internal void OnDeserializingMethod(StreamingContext context) 
    { 
     this.PropertyChanged += 
      new System.ComponentModel.PropertyChangedEventHandler(
       MyGeneratedClass_PropertyChanged); 
    } 

    [OnSerializing] 
    internal void OnSerializingMethod(StreamingContext context) 
    { 
     MyContractResolver cr = context.Context as MyContractResolver; 

     if (cr != null) 
     { 
      cr.AtomarOptinalType("MyAtomarOptionalProperty", 
       this.MyAtomarOptionalPropertySpecified); 
     } 
    } 

    void MyGeneratedClass_PropertyChanged(object sender, 
      System.ComponentModel.PropertyChangedEventArgs e) 
    { 
     if (e.PropertyName == "MyAtomarOptionalProperty") 
     { 
      this.MyAtomarOptionalPropertySpecified = true; 
     } 
    } 
}