How to return a single DataRow object from Asp Web API?

时间:2016-09-01 06:11:29

标签: c# asp.net json asp.net-web-api

So I am writing some Asp.Net WebApi code to hook with old C# back-end code where there is no model class used. (Pure dataTable returned from DataAccess, Crazy right? I know)

Following is the code I put on the Server side.

 public IHttpActionResult GetProduct(int campaignID, int productID)
    {
        var so = new SearchOptions(campaignID)
        {
            ProductID = productID
        };

        var result = SearchManager.Search(so);
        if (result == null || result.Rows.Count == 0)
            return NotFound();
        return Ok(result.Rows[0]);

    }

I am expecting to have the response like this:

{
Field1: "field1",
Field2: "field2",
...
}

But Actually I am having this:

{
  "rowError": "",
  "rowState": 2,
  "table": [
    {
      Field1 : "field1",
      Field2 : "field2",
      ...
    }
  ],
  "itemArray": ["field1","field2"],
  "hasErrors": false
}

I don't want all these rowError, rowState...etc

If I am doing this on the server side:

public IHttpActionResult GetProduct(int campaignID, int productID)
        {
            var so = new SearchOptions(campaignID)
            {
                ProductID = productID
            };

            var result = SearchManager.Search(so);
            if (result == null || result.Rows.Count == 0)
                return NotFound();
            return Ok(result);

        }

I am receiving this:

[{Field1: "field1", Field2: "field2"..}]

which is unfortunately rejected by ngResource get method since it is an array rather than a single Json Object.

What should I do? If I just want to return a single dataRow as a Json string.

Ideally I want to avoid go down to the path of creating an Response Object as suggested by Manoz. (Thank you for your answer Manoz though)

Thanks

3 个答案:

答案 0 :(得分:1)

Did you try deserializing it?

Using NewtonSoft.Json

Create a separate class matching your response. I believe response's format will remain same always.

public class Response{
    public List<response> table{ get;set; }
}

public class response {
    public string Field1 { get;set; }
    public string Field2 { get;set; }
}

Now deserializing response using Newtonsoft.Json

var entities = SearchManager.Search(so);

var result= JsonConvert.DeserializeObject<Response>(entities)
var endResult= result.table[0] //will get you result

Help source - https://www.nuget.org/packages/newtonsoft.json/

答案 1 :(得分:1)

您可以使用LINQ:

DataRow转换为Dictionary
public IHttpActionResult GetProduct(int campaignID, int productID)
{
    var so = new SearchOptions(campaignID)
    {
        ProductID = productID
    };

    var result = SearchManager.Search(so);
    if (result == null || result.Rows.Count == 0)
        return NotFound();

    var row = result.Rows[0];
    return Ok(row.Table.Columns
        .Cast<DataColumn>()
        .ToDictionary(c => c.ColumnName, c => row[c]));
}

该操作可以根据需要返回JSON:{ Field1: "field1", Field2: "field2", ... }

答案 2 :(得分:0)

自几个月前发布以来,假设您正在使用API​​ 2.x.此版本自动且智能地处理返回格式,尤其不需要实现显式CAST。您只需指定所需的类型即可。例如,在AngularJS中,这将告诉API您期望的是什么:

$http({
  method: 'GET',
  responseType: 'json'
  url: ...
}).then(function mySuccess(response){
  $scope.theRow = response.data;
})

在服务器API上,只需保留您的代码即可。在执行期间,它将以JSON格式自动返回结果。