Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return JSON from AWS Lambda Function in C#

Tags:

c#

aws-lambda

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:

  1. I have an AWS Lambda Function written in C#
  2. The return type is "string"
  3. The intention is to consume the return type as JSON
  4. 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\"}]"

  1. Even this variation returns the same:

    string TestJsonEvent = @"[{""FirstName"":""William Smith""}]"; return TestJsonEvent;

like image 781
Simon Peters Avatar asked Oct 16 '25 21:10

Simon Peters


1 Answers

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

like image 149
Dustin Kingen Avatar answered Oct 18 '25 11:10

Dustin Kingen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!