控制属性名称的序列化

控制属性名称的序列化

本文介绍了ASP.NET MVC:使用 JsonResult 控制属性名称的序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用属性来控制JsonResult的JSON输出,类似于你如何使用XmlElementAttribute及其兄弟来控制XML序列化的输出?

Is there a way to control the JSON output of JsonResult with attributes, similar to how you can use XmlElementAttribute and its bretheren to control the output of XML serialization?

例如,给定以下类:

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

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

然后我想得到以下输出:

I'd like to then get the following output:

{ bar: '', oygevalt: '' }

相反:

{ Bar: '', Oygevalt: '' }

推荐答案

我想要一些比 Jarrett 建议的更深入框架的东西,所以我这样做了:

I wanted something a bit more baked into the framework than what Jarrett suggested, so here's what I did:

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

注意:如果您正在寻找比 JsonDataContractSerializer 性能更高的东西,您可以使用 JSON.NET 来做同样的事情.虽然 JSON.NET 似乎没有使用 DataMemberAttribute,但它确实有自己的 JsonPropertyAttribute 可用于完成同样的事情.

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.

这篇关于ASP.NET MVC:使用 JsonResult 控制属性名称的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:24