1

I'm working on WebAPI project.

I have the following method:

public string Get(string a, string b)
{
    return "test";
}

When I send the GET request with Accept: application/json header, the WebAPI returns the following response:

"test"

This response is not valid, it should be:

[
    "test"
]

How can I force the WebAPI to include square brackets in JSON response?

1 Answer 1

1

If you want the returned JSON to contain an array (square brackets), then you need to return an array (or list).

You could do this:

public string[] Get(string a, string b)
{
    return new string[] {"test"};
}

Or something like this:

public List<string> Get(string a, string b)
{
    List<string> list = new List<string>();
    list.Add("test");
    return list;
}

EDIT

To return an object instead of an array, you can make your method like this:

public object Get(string a, string b)
{
    return new { prop = "test" };
}

Note you can also use a strongly typed class in place of object, and return that.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to return a string, but Fiddler and all JSON validators report that "test" is not a valid JSON string. On the other hand, jQuery has no problems parsing that response, so I'm wondering should I return an object which has one property or leave everything as is?
It would probably be better to return an object with one property, for a couple reasons. First, it will definitely satisfy the validators, which will make your life easier once you need to debug things. Second, if you later need to add more info to the response, it is easy to do so if you are already returning an object: just add another property. Conversely, if you start by returning a string, then you'll have to change it to an object at the point that you need to add more info. If it is a published API, then this can cause backward-compatibility issues.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.