Web Api 2 - Custom JSON Serialization Data Type

I'm actually new to Web Api, so my question may seem a little strange.

I have a simple API for returning historical information on price changes. My controller action looks like this:

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

where PriceHistoryRecordModel

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

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

However, the problem is this: the action returns JSON in the following format

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

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

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

So, I wonder

  • if there is a way to achieve such custom serialization?
  • Is it possible to wrap this custom serialization in an attribute and use it as an aspect?
+3
source share
1

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

, :

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

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

, , .

, , .

double[]:

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

, DateTime.Ticks

+3

Source: https://habr.com/ru/post/1676046/


All Articles