ASP.NET MVC:使用JsonResult控制属性名称的序列化
有没有一种方法可以控制JsonResult
with属性的JSON输出,类似于您如何使用XmlElementAttribute
及其属性控制XML序列化的输出?
例如,给定以下类别:
public class Foo{
[SomeJsonSerializationAttribute("bar")]
public String Bar { get; set; }
[SomeJsonSerializationAttribute("oygevalt")]
public String Oygevalt { get; set; }
}
然后,我想获得以下输出:
{ bar: '', oygevalt: '' }
相对于:
{ Bar: '', Oygevalt: '' }
回答:
我想要的东西比Jarrett建议的要多一些,所以这就是我要做的:
public class JsonDataContractActionResult : ActionResult{
public JsonDataContractActionResult(Object data)
{
this.Data = data;
}
public Object Data { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
var serializer = new DataContractJsonSerializer(this.Data.GetType());
String output = String.Empty;
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, this.Data);
output = Encoding.Default.GetString(ms.ToArray());
}
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.Write(output);
}
}
public ActionResult JsonContract(Object data) {
return new JsonDataContractActionResult(data);
}
public ActionResult Update(String id, [Bind(Exclude="Id")] Advertiser advertiser) {
Int32 advertiserId;
if (Int32.TryParse(id, out advertiserId))
{
// update
}
else
{
// insert
}
return JsonContract(advertiser);
}
If you’re looking for something more performant than
JsonDataContractSerializer, you can do the same thing using JSON.NET instead.
While JSON.NET doesn’t appear to utilize DataMemberAttribute, it does have its
own JsonPropertyAttribute which can be used to accomplish the same thing.
以上是 ASP.NET MVC:使用JsonResult控制属性名称的序列化 的全部内容, 来源链接: utcz.com/qa/402900.html