-1

I have a Post method that receives a fairly simple JSON:

{ "First": "John", "Last": "Smith" }

But I need it as a string.

I've tried casting the JSON to a string but it comes up null.

   public void Post([FromBody]string jsonData)
    {
       ...
    }

I would like to use jsonData as a string. I am trying to avoid creating a class with field names matching the JSON because that would mean changing the API every time a field is added. I just need to receive the JSON as a string at the outset. Is there a way to cast it as such at the endpoint without using variable names?

dbc
  • 104,963
  • 20
  • 228
  • 340
John
  • 371
  • 2
  • 4
  • 16
  • is this .net core or something else? – Daniel A. White Aug 15 '19 at 20:03
  • What exactly would this string contain? (given your example json) – mxmissile Aug 15 '19 at 20:04
  • It is Core. The string would contain the JSON in string format. Something I could serialize and de-serialize etc. – John Aug 15 '19 at 20:04
  • If the side that is requesting is javascript, add a `=` and stringify the json object – André Silva Aug 15 '19 at 20:05
  • It is coming in from an external source as an API call. – John Aug 15 '19 at 20:05
  • Hm, then you'll have to create a new class with the properties having the same name and structure as what you're expecting to receive. Use the class you create as the parameter for that method. – André Silva Aug 15 '19 at 20:06
  • That is what I was trying to avoid. That means every time they change the JSON I need to change my class. – John Aug 15 '19 at 20:08
  • You could receive as an object instead of string and see if you can parse it with that newtonsoft library.. I'm shooting in the dark here tbh – André Silva Aug 15 '19 at 20:14
  • Can;t you just grab it from the Request? `var s = Request["parameter"];` – mxmissile Aug 15 '19 at 20:16
  • Actually casting it as an object is correct! – John Aug 15 '19 at 20:30
  • Did you check [ASP.NET Core MVC : How to get raw JSON bound to a string without a type?](https://stackoverflow.com/q/31952002/3744182) or [Access Raw Request Body](https://stackoverflow.com/q/31678990)? – dbc Aug 15 '19 at 20:42
  • May my blog might be able to help you https://ngohungphuc.wordpress.com/2019/01/22/parse-json-string-with-json-net/ – Tony Ngo Aug 16 '19 at 04:45

2 Answers2

1

Just use JToken as parameter.

[HttpPost]
public void PostMethod([FromBody] JToken json)
{
    var jsonAsString = json.ToString();

}
dside
  • 209
  • 2
  • 7
1

Have you try this?

JObject json = JObject.Parse(str);

You might want to refer to Json.NET documentation

Syafiqur__
  • 531
  • 7
  • 15