简体   繁体   中英

How to read a json input in C# using Newtonsoft.Json

Im trying to read json coming into an AWS lambda function, part of the initial code below

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Newtonsoft.Json;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace DemoApp
{
    public class Function
    {
        public string FunctionHandler(dynamic input,ILambdaContext context)
        {
            dynamic results = JsonConvert.DeserializeObject<dynamic>(input);
            String customer = results.customer;
             .......

The incoming json is

{'customer': 'Test Customer',
 'phone': '0435 434 544',
 'asset': 'ASSET',
 'po': 'PO09876',
 'location': 'XYZ',
 'items': {'hose': [[{'goods': 'A231',
     'qty': '0.23',
     'backorder': '0.0',
     'unitprice': '0.0',
     'total': '0.0'},
    {'goods': 'B564',
     'qty': '1.0',
     'backorder': '0.0',
     'unitprice': '0.0',
     'total': '0.0'},
    {'goods': 'C544',
     'qty': '1.0',
     'backorder': '0.0',
     'unitprice': '0.0',
     'total': '0.0'}]],
  'items': []}}

I got an error The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<object>(string)' has some invalid arguments", . How do I read json properly?

JsonConvert.DeserializeObject expects a string so I've converted the json to a string and everything works.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Newtonsoft.Json;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace DemoApp
{
    public class Function
    {
        public string FunctionHandler(Object input,ILambdaContext context)
        {
            string jsonString = System.Text.Json.JsonSerializer.Serialize(input);
            dynamic results = JsonConvert.DeserializeObject(jsonString);
            String customer = results.customer;
             .......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM