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?

4

1 回答 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.

于 2013-09-13T17:16:01.523 回答