Reputation: 4239
I'm new to c# and the whole .net platform so I'm struggling with a lot of what are probably pretty basic things. go easy on me. All I'm trying to do right now is return an array of json objects (as strings, obviously).
[HttpPost]
public string[] PostJsonString([FromBody] string[] arr)
{
return arr;
}
And in Postman, I'm sending
[{"someProp":"someVal"},{ "aThing":"someOtherThing"}]
So painfully simple... Literally only trying to respond with the exact contents of the request body, but for some reason I get back an empty array. Does anyone have any idea why this might be? I've tried returning the array as a string with str.toArray
but then I get back the object type, i.e. "System.String[]"
. I just want a simple JSON response with the objects in an array.
Any tips are appreciated. Even if it's just pointing me to a helpful resource. I've exhausted all the relevant S/O questions and a) don't see one that quite addresses what i'm trying to accomplish, and b) have still tried some of the solutions to no avail.
Upvotes: 5
Views: 4828
Reputation: 5212
[HttpPost]
public JsonResult PostJsonString([FromBody] string[] arr)
{
return Json(arr);
}
Upvotes: 2
Reputation: 3207
Your controller will receive a single string
"[{\"someProp\":\"someVal\"},{ \"aThing\":\"someOtherThing\"}]"
Change the method's signature to
public string PostJsonString([FromBody] string arr)
When you want to work with the JSON array, I recommend using JSON.net
(aka Newtonsoft.Json
) and JArray.Parse or JObject.Parse
using Newtonsoft.Json
// ...
JArray a = JArray.Parse(json);
Upvotes: 1