0

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!

askids
  • 1,406
  • 1
  • 15
  • 32
  • You seem to be answering your own question, as you mention the existence of [JsonArray](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.nodes.jsonarray?view=net-7.0), so could you explain what the problem is with using that? – Tom W Dec 21 '22 at 11:46
  • 1
    if I use [FromBody] JsonArry input, I am not be get pass the validation error in Swagger. I get the below error. "Unable to find a constructor to use for type System.Text.Json.Nodes.JsonArray. Path '', line 1, position 1." – askids Dec 21 '22 at 11:51
  • Works for me in .net 6 - see answer. – Tom W Dec 21 '22 at 14:24

2 Answers2

0

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

Tom W
  • 5,108
  • 4
  • 30
  • 52
  • Thanks Tom. I eventually realized that the issue that I was facing was due to other reason. I was trying this in an existing API that was specifically using Newtonsoft by having AddNewtonsoftJson. So input was going through validation applied by that library. So looks like either I will have to port remaining functionality out to also use System.Text.Json or continue using JArray for this requirement also. I am going to accept this as answer. – askids Dec 22 '22 at 00:12
0

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

dbc
  • 104,963
  • 20
  • 228
  • 340
Washyn Acero
  • 174
  • 1
  • 8