| ■87920 / ) |
Re[1]: Webサービスからのタグなし項目を取得時の挙動 |
□投稿者/ WebSurfer (1557回)-(2018/07/13(Fri) 12:49:58)
|
■No87907 (雪だるま さん) に返信
> 環境はVisual Studio 2010でVBです。
PANG2 さんのレスから想像を膨らませてみました。
xml 上で NULL を表すのが既定では要素が存在しないということになるそうですが、それを「Web
サービスからタグなしで返却」と言っていたのだと理解します。
以下の Web サービスの GetLong メソッドの戻り値は long? 型でこの例では null を返します。
GetDataTable は SQL Server DB のテーブルの全レコードを DataTable に取得して返しますが、
その最初のレコードの CategoryID が NULL になっています。
<%@ WebService Language="C#" Class="NorthwindProductsWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using NorthwindProducts;
using NorthwindProducts.ProductsDataSetTableAdapters;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class NorthwindProductsWebService : System.Web.Services.WebService
{
[WebMethod]
public long? GetLong()
{
return null;
}
[WebMethod]
public ProductsDataSet.ProductsDataTable GetDataTable()
{
ProductsDataSet.ProductsDataTable datatable = new ProductsDataSet.ProductsDataTable();
ProductsTableAdapter adapter = new ProductsTableAdapter();
adapter.Fill(datatable);
return datatable;
}
}
それをクライアント側のアプリで取得すると GetLong は null を返しますので null が返ってき
たら "N/A" と表示すれば良いはずです。
GetDataTable は DataTable を返しますが、DB で NULL になっているとその行・列のデータは
DBNull 型になっているので、その場合は "N/A" とすればよいはずです。
以下のその例を示します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace ConsoleAppWebService
{
class Program
{
static void Main(string[] args)
{
ServiceReference1.NorthwindProductsWebServiceSoapClient client =
new ServiceReference1.NorthwindProductsWebServiceSoapClient();
long? value = client.GetLong();
Console.WriteLine("Result of GetLong: {0}", (value == null) ? "N/A" : value.ToString());
ServiceReference1.ProductsDataSet.ProductsDataTable table = client.GetDataTable();
for (int i = 0; i < 5; i++)
{
string categoryId = (table[i][table.CategoryIDColumn] is DBNull) ?
"N/A" : table[i][table.CategoryIDColumn].ToString();
Console.WriteLine("Name: {0}, SupplierID: {1}, CategoryID: {2}",
table[i].ProductName, table[i].SupplierID, categoryId);
}
// 結果は:
// Result of GetLong: N/A
// Name: Chai, SupplierID: 1, CategoryID: N / A
// Name: Chang, SupplierID: 1, CategoryID: 1
// Name: Aniseed Syrup, SupplierID: 1, CategoryID: 2
// Name: Chef Anton's Cajun Seasoning, SupplierID: 2, CategoryID: 2
// Name: Chef Anton's Gumbo Mix, SupplierID: 2, CategoryID: 2
}
}
}
|
|