如何使用自定义格式化程序进行JSON序列化 [英] How do I use a custom formatter for json serialization

查看:114
本文介绍了如何使用自定义格式化程序进行JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我手动创建一个符合我们标准json响应对象格式的json对象,该格式对于错误和实际响应都是相同的:

In the code below I am manually creating a json object that adheres to our standard json response object format, which is the same for both errors and actual responses:

{数据:{/* something */},状态:{httpCode:123,消息:错误消息"}}

如何配置ASP.NET为我做这种格式化?显然可以使用标准的

How can I configure ASP.NET to do this formatting for me? It can obviously do so using the standard JSON and XML formatter when doing content negotiation, but the linked article only points to a page on Custom Formatters that is blank (and also for ASP.NET MVC which I am not using)...

我还希望它能够在响应对象中设置返回的http代码(如下所示).

I would also like for it to be able to set the returned http code in the response object (as shown below).

当前的json手动格式

[StandardizedRestServiceExceptionFilter]
public class FooController : ApiController
{
    /// <summary>
    /// 
    /// The return format for both real results and errors
    /// is { data : { }, status : { httpCode : 123, message: "error message" }
    ///
    /// We have moved the error serialization to StandardizedRestServiceExceptionFilter,
    /// but was unable to generalize the processing of the output format for normal responses
    /// That could be improved, possibly using a IMessageFormatter ?
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns
    [HttpGet]
    public JObject Coverage(string code)
    {
        dynamic returnObject = new JObject();
        dynamic statusObject = new JObject();
        dynamic dataObject = new JObject();

        JArray stores = StoresWithCoverage(code);
        var hasCoverage = stores.Count > 0;
        dataObject.coverage = hasCoverage;

        returnObject.data = dataObject;
        returnObject.status = statusObject;

        statusObject.message = "";
        statusObject.httpCode = 200;

        return returnObject;
        }
    }
}

因此,在上面的示例中,我希望能够仅返回具有 coverage 属性的某种对象,并让ASP.NET对JSON进行实际的格式设置和序列化(如果在内容协商).

So in the above example I would like to be able to just return an Object of some kind with a coverage property and have ASP.NET do the actual formatting and serialization to JSON (if requested in the content negotiation).

推荐答案

一个人可以使用预先构建或自定义的

One can either use prebuilt or custom Media Formatters using the ASP.NET Web API.

在这种情况下,可以以上面链接中的自定义格式器为例,并根据自己的需要修改JSON内容包装器(此处:使用

In this case, one could take the custom formatter from the link above as an example, and modify the JSON content wrapper to one's needs (here: using JSON.NET):

首先,您需要指定要支持的内容类型:

First you need to specify which content type you are supporting:

public CustomJsonFormatter()
{
    // Add the supported media type.
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}

然后,您需要实现对 WriteToStream 方法的覆盖:

Then you you need to implement your override of the WriteToStream method:

public override void WriteToStream(Type type, object value, Stream  writeStream, HttpContent content)
{
    using (var writer = new StreamWriter(writeStream, effectiveEncoding))
    {
        using (JsonWriter jw = new JsonTextWriter(writer))
        {
            dynamic returnObject = new JObject();
            dynamic status = new JObject();
            JObject data = (JObject)JToken.FromObject(value);

            status.httpCode = HttpContext.Current.HttpResponse.StatusCode;
            status.message = null;

            returnObject.data = data;
            returnObject.status = status;

            jw.Formatting = Formatting.Indented;

            JsonSerializer serializer = new JsonSerializer();
            // for customizing settings, like lower casing
            // attribute names, see http://stackoverflow.com/a/6288726/200987
            serializer.ContractResolver = new CamelCasePropertyNamesContractResolver()

            serializer.Serialize(jw, returnObject);
        }
    }
}

最后,我们需要说出哪种类型支持转换,并向ASP.NET注册此格式化程序,以及进行其他一些较小的(通常是不需要的)修改.请参阅下面的文章,以了解如何执行此操作以及序列化,http状态代码和内容协商的工作方式并可以对其进行自定义.

And finally one needs to say which type one support transforming, register this formatter with ASP.NET, and some other minor (and usually non-required) modifications. Refer to the articles below for how to do this, as well as how serialization, http status codes and content negotiation works and can be customized.

这篇关于如何使用自定义格式化程序进行JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆