JSON请求WCF对象数组参数

时间:2010-12-06 14:05:26

标签: android wcf json

我在网上搜索了2天的答案后就问了这个问题。

好的,这就是事情:

在服务器端,我有一个WCF Web服务,定义如下:

namespace HelloRest
{
[System.ServiceModel.ServiceContract]
public interface IHelloRest
  {
    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "SaveVehicle",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    string SaveVehicle(clVehicles vehicles);
  }
}

namespace HelloRest
{
  public class HelloRestService : IHelloRest
{
   public string SaveVehicle(clVehicles vehicles)
    {
    ...
    }
}
}


namespace WebApplication1
{

    [Serializable]
    [DataContract]
    public class clVehicles
    {
        [DataMember]
        public List<Vehicle> Vehicles { get; set; }
    }
}


namespace WebApplication1
{

    [Serializable]
    [DataContract]
    public class Vehicle
    {

        [DataMember(Name = "year")]
        public int Year
        {
            get;
            set;
        }

        [DataMember(Name = "plate")]
        public string Plate
        {
            get;
            set;
        }

        [DataMember(Name = "make")]
        public string Make
        {
            get;
            set;
        }

        [DataMember(Name = "model")]
        public string Model
        {
            get;
            set;
        }
    }    
}

我试图通过Android使用这个网络服务,这样:

HttpPost request = new HttpPost(Consts.URL + "/SaveVehicle");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");

JSONStringer v = new JSONStringer();
v.object();
v.key("Vehicles");
v.object();
v.key("plate").value(plate);
v.key("make").value(make);
v.key("model").value(model);
v.key("year").value(Integer.parseInt(year.toString()));
v.endObject();
v.endObject();
JSONArray arr = new JSONArray();
arr.put(v);

JSONStringer vehicle = new JSONStringer();
vehicle.object();
vehicle.key("vehicles").value(arr);
vehicle.endObject();

StringEntity entity = new StringEntity(vehicle.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

问题:

当我启动客户端时,请求被转发到服务器(我在“SaveVehicle”函数中有一个断点)。

问题在于函数的参数:“vehicles” - 这个对象(假设为)只包含一个成员 - “Vehicles”,其类型为:List。 无论我从客户端发送什么,我都会为这个内部容器(“车辆”)获得空值。

我几乎尝试了一切!我确定问题出在JSONStringer地区的某个地方......

1 个答案:

答案 0 :(得分:1)

找到答案: 按以下方式定义您的课程:

namespace WebApplication1
{
 [KnownType(typeof(Vehicle))]
 [DataContract]
 public class Vehicle
 {
 }
}


namespace WebApplication1
{
 [CollectionDataContract]
 [KnownType(typeof(Vehicle))]
 public class clVehicles: List<Vehicle>
 {      
 }
}