return JSON from AWS Lambda Function in C#

aws-lambda, c#

Solution

Amazon has examples in their announcement for C# support and Lambda Function Handler documentation.

Relevant bits:

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 the `ILambdaSerializer` interface provided by the `Amazon.Lambda.Core` library.

To add the default serializer attribute to a method, first add a dependency on `Amazon.Lambda.Serialization.Json`[...]

Install the Amazon.Lambda.Serialization.Json[1] NuGet package and import a reference the `Amazon.Lambda.Serialization.Json` namespace.

public class Sample
{
    [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
    public object Test()
    {
        return new { FirstName = "William Smith" };
    }
}

[1]: Github link

Problem

Problem: Output looks like this [{\"FirstName\":\"William Smith\"}]" Question: How can I return a string that has well formatted JSON from an AWS Lambda Function written in C#? Details: - I have an AWS Lambda Function written in C# - The return type is "string" - The intention is to consume the return type as JSON This is what the C# Lambda function is coded to return: string TestJsonEvent = "[{\"FirstName\":\"William Smith\"}]"; return TestJsonEvent; When the Lambda function executes; it returns: "[{\"FirstName\":\"William Smith\"}]" Even this variation returns the same: string TestJsonEvent = @"[{""FirstName"":""William Smith""}]"; return TestJsonEvent;

Original source