1 回答
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是一個(gè)簡(jiǎn)單的例子:
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 函數(shù)中,您將擁有以下內(nèi)容:
[assembly: LambdaSerializer(typeof(MySerializer.LambdaSerializer))]
namespace MyNamespace
{
public MyReturnObject FunctionHandler(MyInObject p, ILambdaContext context)
{
}
請(qǐng)注意,顯式實(shí)現(xiàn)接口不起作用:
void ILambdaContext.Serialize<T>(T response, Stream responseStream)
{
// won't work
不要問(wèn)我為什么。我的猜測(cè)是 AWS 創(chuàng)建對(duì)象并且不將其轉(zhuǎn)換為接口但期望公共方法。
您實(shí)際上可以在那里找到序列化程序源代碼,但我目前找不到。如果我遇到它,我會(huì)編輯這篇文章。
根據(jù)我的經(jīng)驗(yàn),只使用了默認(rèn) ctor,但為了安全起見(jiàn),您可能應(yīng)該將其默認(rèn)轉(zhuǎn)換器添加到您的序列化程序中。我現(xiàn)在不打擾,不過(guò)還好。
希望這可以幫助。
- 1 回答
- 0 關(guān)注
- 150 瀏覽
添加回答
舉報(bào)
