问题:输出看起来像这样 [{\"FirstName\":\"William Smith\"}]"
问题:如何从用 C# 编写的 AWS Lambda 函数返回格式正确的 JSON 字符串?
详细信息:
- 我有一个用 C# 编写的 AWS Lambda 函数
- 返回类型为“字符串”
- 目的是将返回类型作为 JSON 使用
这是 C# Lambda 函数编码返回的内容:
string TestJsonEvent = "[{\"FirstName\":\"William Smith\"}]"; 返回 TestJsonEvent;
当 Lambda 函数执行时;它返回: "[{\"名字\":\"威廉·史密斯\"}]"
即使这个变体也返回相同的结果:
string TestJsonEvent = @"[{""FirstName"":""William Smith""}]"; 返回 TestJsonEvent;
最佳答案
Amazon 在他们的 announcement for C# support 中有示例和 Lambda Function Handler文档。
相关位:
Handling Standard Data Types
All other types, as listed below, require you to specify a serializer.
- Primitive .NET types (such as string or int).
- Collections and maps - IList, IEnumerable, IList, Array, IDictionary, IDictionary
- POCO types (Plain old CLR objects)
- Predefined AWS event types
- For asynchronous invocations the return-type will be ignored by Lambda. The return type may be set to void in such cases.
- If you are using .NET asynchronous programming, the return type can be Task and Task types and use async and await keywords. For more information, see Using Async in C# Functions with AWS Lambda.
Unless your function input and output parameters are of type
System.IO.Stream
, you will need to serialize them. AWS Lambda provides a default serializer that can be applied at the assembly or method level of your application, or you can define your own by implementing theILambdaSerializer
interface provided by theAmazon.Lambda.Core
library.To add the default serializer attribute to a method, first add a dependency on
Amazon.Lambda.Serialization.Json
[...]
安装 Amazon.Lambda.Serialization.Json [1] NuGet 打包并导入对 Amazon.Lambda.Serialization.Json
命名空间的引用。
public class Sample
{
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
public object Test()
{
return new { FirstName = "William Smith" };
}
}
[1]: Github link
关于c# - 从 C# 中的 AWS Lambda 函数返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43904822/