Web Api 2-自定义数据类型JSON序列化 [英] Web Api 2 - custom data type JSON serialization

查看:153
本文介绍了Web Api 2-自定义数据类型JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是Web Api的新手,所以我的问题听起来有点奇怪.

I'm actually new to Web Api, so my question may sound a bit odd.

我有简单的API,可以返回有关价格变化的历史信息.我的控制器的动作如下所示:

I have simple API to return historical information about price changes. My controller's action looks like this:

[HttpGet]
[Route("api/history/{id}/{size}")]
public async Task<IEnumerable<PriceHistoryRecordModel>> GetHistory(string id, Size size)

PriceHistoryRecordModel在哪里

where PriceHistoryRecordModel is

[DataContract]
public class PriceHistoryRecordModel
{
    [DataMember]
    public DateTime Date { get; set; }

    [DataMember]
    public double Value { get; set; }
}

但是,问题是-操作以以下格式返回JSON

However, the problem is - action returns JSON in following format

[{"Date":"2016-02-07T08:22:46.212Z","Value":17.48},{"Date":"2016-02-08T09:34:01.212Z","Value":18.37}]

但是,由于客户端对数据格式的特定要求,我需要使用JSON来显示这种方式

but, due to specific client requirements to data format, I need my JSON to look this way

[[1238371200000,17.48],[1238457600000,18.37]]

所以,我想知道

  • 是否有一种方法可以实现这种自定义序列化?
  • 我可以将此自定义序列化包装到属性中并将其用作一个方面吗?

推荐答案

您可以这样编写CustomConverter:

public class CustomCoverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            PriceHistoryRecordModel obj = value as PriceHistoryRecordModel;
            JToken t = JToken.FromObject(new double[] { obj.Date.Ticks, obj.Value });
            t.WriteTo(writer);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(PriceHistoryRecordModel).IsAssignableFrom(objectType);
        }
    }

指定我们的类已通过此转换器序列化:

Specify that our class is serialized by this converter:

[JsonConverter(typeof(CustomCoverter))]
[DataContract]
public class PriceHistoryRecordModel
{
    [DataMember]
    public DateTime Date { get; set; }

    [DataMember]
    public double Value { get; set; }
}

它可以工作,但是如果您只在这种特定情况下需要这种特殊处理,那是一种开销.

It works, but it's kind of overhead if you only need this special treatment in this specific case.

如果您有许多类似的情况,则可以让您的类实现一个基类,并将此转换器用于所有这些类.

In case you have many similar cases like this, you can have your classes implement a base class and use this converter for all these classes.

在这种简单情况下,一种快速的解决方案是将返回类型更改为double[]:

In this simple case, a quick solution is just to change your return type to double[]:

public async Task<IEnumerable<double[]>> GetHistory(string id, Size size)

并使用DateTime.Ticks

这篇关于Web Api 2-自定义数据类型JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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