为了账号安全,请及时绑定邮箱和手机立即绑定

自定义序列化程序设置

自定义序列化程序设置

C#
翻阅古今 2022-07-23 17:13:57
我正在创建一个 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 回答

?
杨魅力

TA贡献1811条经验 获得超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,但为了安全起见,您可能应该将其默认转换器添加到您的序列化程序中。我现在不打扰,不过还好。


希望这可以帮助。


查看完整回答
反对 回复 2022-07-23
  • 1 回答
  • 0 关注
  • 115 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号