代码之家  ›  专栏  ›  技术社区  ›  TrialAndError

自定义序列化程序设置

  •  0
  • TrialAndError  · 技术社区  · 6 年前

    我正在创建一个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?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Adam Benson    6 年前

    下面是一个简单的例子:

    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,但为了安全起见,您可能应该将它们的默认转换器添加到序列化程序中。我现在不麻烦了,不过还可以。

    希望这有帮助。

    亚当。