繁体   English   中英

自定义序列化器设置

[英]Custom Serializer Settings

我正在创建一个AWS Lambda函数,该函数将接收JSON有效负载并对其进行处理。 使用C#SDK,他们提供了一个基于Newtonsoft.Json的序列化程序。

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

我需要为日期指定自定义格式,以便可以将内容正确反序列化为.NET类。

在Newtonsoft.Json中,我可以这样定义自定义设置:

new JsonSerializerSettings()
{
    DateFormatString = "yyyyMMdd",
    Formatting = Formatting.Indented,
    NullValueHandling = NullValueHandling.Ignore
};

我在文档中找不到任何地方,也无法在Amazon实现中找到其他方法。 有人定制过LambdaSerializer吗?

这是一个简单的例子:

using System;
using System.Collections.Generic;
using System.IO;

using Amazon.Lambda.Core;

namespace MySerializer
{
    public class LambdaSerializer : ILambdaSerializer
    {

        public LambdaSerializer()
        {
        }


        public LambdaSerializer(IEnumerable<Newtonsoft.Json.JsonConverter> converters) : this()
        {
            throw new NotSupportedException("Custom serializer with converters not supported.");
        }


        string GetString(Stream s)
        {
            byte[] ba = new byte[s.Length];

            for (int iPos = 0; iPos < ba.Length; )
            {
                iPos += s.Read(ba, iPos, ba.Length - iPos);
            }

            string result = System.Text.ASCIIEncoding.ASCII.GetString(ba);
            return result;
        }


        public T Deserialize<T>(Stream requestStream)
        {
            string json = GetString(requestStream);
            // Note: you could just pass the stream into the deserializer if it will accept it and dispense with GetString()
            T obj = // Your deserialization here
            return obj;
        }


        public void Serialize<T>(T response, Stream responseStream)
        {
            string json = "Your JSON here";
            StreamWriter writer = new StreamWriter(responseStream);
            writer.Write(json);
            writer.Flush();
        }

    } // public class LambdaSerializer

}

在您的lambda函数中,您将具有以下功能:

[assembly: LambdaSerializer(typeof(MySerializer.LambdaSerializer))]

namespace MyNamespace
{

   public MyReturnObject FunctionHandler(MyInObject p, ILambdaContext context)
   {

   }

请注意,显式实现接口不起作用:

void ILambdaContext.Serialize<T>(T response, Stream responseStream)
{
   // won't work

不要问我为什么。 我的猜测是AWS创建对象并且不将其强制转换为接口,而是期望使用公共方法。

您实际上可以在那里找到序列化程序源代码,但目前无法找到。 如果碰到它,我将编辑这篇文章。

以我的经验,仅使用默认的ctor,但是为了安全起见,您应该将其默认转换器添加到序列化器中。 我现在不打扰,但是还可以。

希望这可以帮助。

亚当。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM