Home > Software design >  how to get http post request body without property in c#
how to get http post request body without property in c#

Time:02-03

I am creating an API. Where I have to accept JSON data. I found the JSON not properly fit with my property class. In this scenario how should I get data from post request?

enter image description here

I have tried with WEB API but it's showing null error System.NullReferenceException: 'Object reference not set to an instance of an object.'

enter image description here

CodePudding user response:

You cannot always change the class like @GuruStron suggests. Because it could have dependencies on other parts of the program.

What you should do : Customize your JSON parser

You probably already use Newtonsoft to parse your incoming body request into your class. Now what you need is to customize that parser so it fit your need.

Here is the doc: How to create a custom JsonCoverter

If you don't use Newtonsoft you probably use default System.TextJson in that case here are the docs

No matter which "parser" you use, you'll probably find an equivalent on the web

Please provide more details (and some code) for a more precise answer.

CodePudding user response:

I don't know if you are receiving the json via an HttpClient, but in the case you can use ExpandoObject or dynamic as read target from the content.

es.

var response = await httpClient.GetAsync(url);
var result = await response.Content.ReadFromJsonAsync<dynamic>();        

or

var result = await response.Content.ReadFromJsonAsync<ExpandoObject>();        

In any case, case the deserialization to dynamic or ExpandoObject could work also from a string (see this).

  • Related