AWS Lambda (.NET) + SQS: Error converting the Lambda event JSON payload to a string
Asked Answered
P

3

5

i use AWS Lambda (.NET Core 2.1 environment) + SQS as trigger

The problem is that my lambda cannot parse my SQS message.

Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example "Hello World" in order to be converted to a string: Unexpected character encountered while parsing value: {. Path '', line 1, position 1.: JsonSerializerException

Here is declaration of my handler:

public async Task<string> FunctionHandler(DummyMessage message, ILambdaContext context)

Model:

public class DummyMessage {
  public string Label { get; set; }
}

SQS input from AWS Console that I tried: {"Label":"qwerty"}, "{"Label":"qwerty"}", "{\"Label\":\"qwerty\"}", but same error occurs.

Could you please help with this issue?

Pipe answered 18/2, 2020 at 9:27 Comment(0)
E
11

When passing Json try JObject from Newtonsoft.Json.Linq

FunctionHandler(JObject eventStr, ILambdaContext context)

and then you can Deseralize the response where SQSEvent is inherited from Amazon.Lambda.SQSEvents SDK Library.

var result = eventStr.ToObject<SQSEvent>();
Er answered 18/2, 2020 at 11:23 Comment(0)
S
5

Also, do not forget to add/change aws serializer :

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace AwsLambdaHandleTelegramWebhooks
{
   public class Function
   {
      public  APIGatewayProxyResponse FunctionHandler(JObject input,ILambdaContext context)
      {
Studdingsail answered 2/6, 2020 at 23:36 Comment(0)
S
0

What Solved My problem : I used [LambdaSerializer(typeof(Newtonsoft.Json.JsonSerializer))] on the Function Handler

and Assigned [JsonProperty("")] attribute to all POCO class Properties

and directly used the POCO class in the Handler Signature FunctionHandler(MyPocoClass input, ILambdaContext context)

The following is my Call in MAIN :

 private static async Task Main(string[] args)
    {
        Func<MyPocoClass , ILambdaContext, string> handler = FunctionHandler;
        await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer())
            .Build()
            .RunAsync();
    }

Following is My Handler Method:

[LambdaSerializer(typeof(Newtonsoft.Json.JsonSerializer))]
public static string FunctionHandler(MyPocoClass input, ILambdaContext context)
{
   // logic
}

MyPoco Class :

public class MyPocoClass
{
     [JsonProperty("MyProperty")]
     public string? MyProperty{ get; set; }
    
}
Snips answered 16/6, 2022 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.