一說在需要的時候來定製的輸出格式,序列化工作時,人們已經用變通的就是創建一個字符串屬性:
[DataMember(Name = "price", Order = 23)]
[XmlElement("price", Order = 23)]
public string Price_String
{
get
{
return Formatter.FormatAsCurrency(this.Price);
}
set
{
this.Price = Formatter.ParseCurrency(value);
}
}
[XmlIgnore]
public decimal Price { get; set; }
格式化爲一個自定義類我有HANDELS解析/格式化爲特定的類型。這是不相關的,但我會包括他們:
public static string FormatAsCurrency(decimal? amount)
{
return amount.HasValue ? String.Format("{0:C}USD", amount).Replace("$","") : null;
}
public static decimal ParseCurrency(string value)
{
return !String.IsNullOrEmpty(value) ? decimal.Parse(value.Replace("USD", "")) : 0;
}
public static decimal? ParseNullableCurrency(string value)
{
return !String.IsNullOrEmpty(value) ? decimal.Parse(value.Replace("USD", "")) as decimal? : null;
}
在我的例子,我打上了我的兩個DataContract和XML序列化的屬性。這並不理想,但當時是唯一的解決方法。
我也是在我的控制器中創建一個方法返回一個響應「
public ContentResult GetContentResult(object responseObject)
{
#region Output Format
if (this.ResponseFormat == ResponseFormatEnum.JSON)
{
string json = "";
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer jsonserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(responseObject.GetType());
MemoryStream ms = new MemoryStream();
jsonserializer.WriteObject(ms, responseObject);
json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
ms.Dispose();
jsonserializer = null;
}
catch(System.Exception ex)
{
string err = ex.Message;
}
return new ContentResult() { Content = json, ContentType = "application/json" };
}
else
{
string xml = "";
try
{
MemoryStream ms = new MemoryStream();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(responseObject.GetType());
System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add("", "");
ms = new MemoryStream();
serializer.Serialize(ms, responseObject, ns);
xml = Encoding.Default.GetString(ms.ToArray()); ms.Close();
ms.Dispose();
serializer = null;
}
catch (System.Exception ex)
{
throw ex;
}
return new ContentResult() { Content = xml, ContentType = "text/xml" };
}
#endregion
}
,並使用它:
public ActionResult Feed()
{
ViewModels.API.Deals.Response response = new ViewModels.API.Deals.Get();
return GetContentResult(response);
}
我的例子是有點比更復雜的是你正在使用,但它作品(對於XML和JSON)
以編程方式,如何讀取其屬性的DisplayFormat設置的對象? – 2012-03-02 20:48:52