小编典典

ASP.NET MVC:使用JsonResult控制属性名称的序列化

json

有没有一种方法可以控制JsonResultwith属性的JSON输出,类似于您如何使用XmlElementAttribute及其属性控制XML序列化的输出?

例如,给定以下类别:

public class Foo
{
    [SomeJsonSerializationAttribute("bar")]
    public String Bar { get; set; }

    [SomeJsonSerializationAttribute("oygevalt")]
    public String Oygevalt { get; set; }
}

然后,我想获得以下输出:

{ bar: '', oygevalt: '' }

相对于:

{ Bar: '', Oygevalt: '' }

阅读 384

收藏
2020-07-27

共1个答案

小编典典

我想要的东西比Jarrett建议的要多一些,所以这就是我要做的:

JsonDataContractActionResult:

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);
    }
}

JsonContract()方法,添加到我的基本控制器类中:

    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);
    }

Note: 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.

2020-07-27