Одним из способов обхода, которые люди использовали при настройке выходного формата при работе с сериализацией, является создание строкового свойства:
[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; }
Formatter - это мой собственный класс, который разбирает / форматирует для определенных типов. Они не актуальны, но я включу их:
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)