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,但为了安全起见,您可能应该将其默认转换器添加到您的序列化程序中。我现在不打扰,不过还好。
希望这可以帮助。
- 1 回答
- 0 关注
- 115 浏览
添加回答
举报