5

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.

3
  • 1
    your json doesn't represent a string array, its more like a dictionary or custom object. A string array would be ["someProp", "someVal", "aThing", "someOtherThing"] Commented Jan 21, 2016 at 21:17
  • ahhh. mkay. @Jonesopolis, i gotcha. so even though the json is technically a string (being that http doesn't actually know what an object is, right?), it still behaves as an object? is that correct? Commented Jan 21, 2016 at 21:30
  • @B.ClayShannon danke, herr Shannon. I've looked at it, but I guess I just didn't realize that the JSON was already behaving as objects when being sent via http. Commented Jan 21, 2016 at 21:32

2 Answers 2

2
[HttpPost]
public JsonResult PostJsonString([FromBody] string[] arr)
{
    return Json(arr);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

SUCCESS! Thanks, mate. [HttpPost] public JArray PostJsonString([FromBody] string arr) { JArray a = JArray.Parse(arr); return a; } also, i wasn't sending the array inside a string initially. i reformatted my request from [json in here] to '[json in here]'. just a note for posterity. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.