Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle JSON data in POST request in C# (.NET Core 3.1)

Previously (In .Net Core 2.1) I successfully handled JSON data with below method

[HttpPost]
[Route("sendJsonData")]
public JObject saveTemplate(JObject jsonString)
{

        string templateName = (string)jsonString.SelectToken("templateName");
        string filePathAndName = "D:\\" + "templates\\" + templateName + ".txt";

        using (StreamWriter file = File.CreateText(@filePathAndName))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(file, jsonString);
        }

    return jsonString;
}

But when I created the same method with .Net Core 3.1. It is not working showing some error with JObject. I am getting that JSON from below code

onSubmit() {
this.http.post("https://localhost:44350/ReportAPI/sendJsonData", this.surveyForm.value)
            .subscribe(
                data => console.log("success!", data),
                error => console.error("couldn't post because", error)
            );
}

Below is the error (Response from Postman)

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|6e209814-4dd7396cc2dfa182.",
    "errors": {
        "$": [
            "The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Newtonsoft.Json.Linq.JToken]. Path: $ | LineNumber: 0 | BytePositionInLine: 14."
        ]
    }
}

JSON

{  
   "templateName":"BFS Survey",
   "surveyQuestions":[  
      {  
         "questionTitle":"Name",
         "questionType":"Text",
         "questionGroup":{  

         }
      },
      {  
         "questionTitle":"Age",
         "questionType":"Number",
         "questionGroup":{  

         }
      },
      {  
         "questionTitle":"Gender",
         "questionType":"Single choice",
         "questionGroup":{  
            "options":[  
               {  
                  "optionText":"Male"
               },
               {  
                  "optionText":"Female"
               },
               {  
                  "optionText":"Other"
               }
            ],
            "showRemarksBox":false
         }
      },
      {  
         "questionTitle":"Skills",
         "questionType":"Multi choice",
         "questionGroup":{  
            "options":[  
               {  
                  "optionText":"Java"
               },
               {  
                  "optionText":"Angular"
               },
               {  
                  "optionText":"Python"
               },
               {  
                  "optionText":"R"
               }
            ],
            "showRemarksBox":false
         }
      }
   ]
}

Code perfectly worked using .Net Core 2.1 but not working with 3.1. Please suggest me how resolve this issue.

like image 532
Abhi Avatar asked Dec 05 '19 07:12

Abhi


People also ask

Can we send JSON object in post request?

Specify the POST data: As per the HTTP specification for a POST request, we pass data through the message body. Using requests, you'll pass the payload to the corresponding function's data parameter. Data can be anything including JSON, dictionary, a list of tuples, bytes, or a file-like object.

Can we send JSON object in post request in REST API?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

Does POST use JSON?

To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.


1 Answers

In order to migrate from ASP.NET Core 2.x to 3.0, refer to this link:

  • Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson
  • Add in Startup.cs, in method ConfigureServices: services.AddMvc().AddNewtonsoftJson();
like image 95
Rahul Sharma Avatar answered Sep 19 '22 17:09

Rahul Sharma