Home > database >  How to accept JsonArray as input to WebAPI
How to accept JsonArray as input to WebAPI

Time:12-22

I am using .Net 6 WebAPI. I need to accept a generic JSON array as input. The properties present in each JSON document is not known before. So I cannot Deserialize to specific object type. So I am looking for 2 inputs. a) What should be input datatype to accept this in body, when using System.Text.Json? Previously, we have used JArray using JSON.NET. b) How can I then read this input as an array so that I can then convert into generic JsonObject type?

[
  { "prop1" : "value1", "prop2" : "value1"},
  { "prop3" : "value3", "prop4" : "value4"},
  { "propx" : "valuex", "propy" : "value6", "nested": { "other": [1,23,45] }}
]

I am also open to option of accepting NDJSON.

Thanks!

CodePudding user response:

If all I do is create a new .net Web API from the standard template and add the following action:

    [HttpPost]
    public async Task<IActionResult> Post(JsonArray array)
    {
        foreach(var node in array)
        {
            Console.WriteLine(node);
        }
        return Ok();
    }

And pass the content you have specified in the question using the built-in swagger UI:

example of using swagger UI to test the posted example

And I can step through in the debugger and observe that the request has been deserialized to do what I please with:

enter image description here

CodePudding user response:

From body you can receive ([FromBody]List<object> input) or ([FromBody]List<dynamic> input) and access to properties dynamically or serialize to typed objects.

  • Related