我创建了新的WCF REST服务但是我的结果没有键(不是JSON数组格式) 我的结果是这样的
{"email": "abc@gmail.com",
"name": "John",
"mobile": "009854"}
我想创建一个名为Info的数组,其中每个元素都包含这三个值。
"Info":
[
{
"email": "abc@gmail.com",
"name": "John",
"mobile": "009854"
},
{
"email": "safft@gmail.com",
"name": "Smith",
"mobile": "009114"
}
]
我的c#代码
public OrderContract GetOrderDetails(string OrderID)
{
OrderContract order = new OrderContract();
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ssd"].ConnectionString);
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Stu where Client_id='" + OrderID + "'", con);
DataSet ds = new DataSet();
da.Fill(ds, "contacts");
order.email= ds.Tables["contacts"].Rows[0]["email"].ToString();
order.name = ds.Tables["contacts"].Rows[0]["name"].ToString();
order.mobile= ds.Tables["contacts"].Rows[0]["mobile"].ToString();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return order;
}
任何人都可以帮助我?
在此行中显示错误“对象引用未设置为对象的实例。”
infoContract.Info.Add(order );
我的代码就像这样
public InfoContract GetOrderDetails(string OrderID)
{
OrderContract order = new OrderContract();
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ssd"].ConnectionString);
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Stu where Client_id='" + OrderID + "'", con);
DataSet ds = new DataSet();
da.Fill(ds, "contacts");
order.email= ds.Tables["contacts"].Rows[0]["email"].ToString();
order.name = ds.Tables["contacts"].Rows[0]["name"].ToString();
order.mobile= ds.Tables["contacts"].Rows[0]["mobile"].ToString();
var infoContract = new InfoContract();
infoContract.Info.Add(order );
return infoContract;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return order;
}
我的界面
public interface IOrderService
{
[OperationContract]
[WebGet(UriTemplate = "/GetOrderDetails/{OrderID}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
InfoContract GetOrderDetails(string OrderID);
}
我的班级是
[DataContract]
public class OrderContract
{
[DataMember]
public string email{ get; set; }
[DataMember]
public string name{ get; set; }
[DataMember]
public string mobile{ get; set; }
}
[DataContract]
public class InfoContract
{
[DataMember]
public List<OrderContract> Info { get; set; }
}
答案 0 :(得分:6)
您必须返回一个数组。
您的方法只返回一个对象,您可以尝试使用类似于下面给出的内容。
public InfoContract GetOrderDetails(string OrderID){
...
var infoContract = new InfoContract();
infoContract.Info.Add(order );
return infoContract;
}
OrderContract.cs
public class OrderContract {
public string email {get;set;}
public string name {get;set;}
public string mobile{get;set;}
}
public class InfoContract {
public List<OrderContract> Info {get;set;}
}