シリアライズでの作業は文字列プロパティを作成するときに、出力形式をカスタマイズする必要時に人々が使用している回避策の一つに:
[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設定用のオブジェクトをどのように読み込むのですか? –