I am trying to POST JSON to a WCF service. The json object contains an array. I'm wondering how to correctly bind to my data contract. If anyone can give me a pointer here I would really appreciate it. Currently my cart object is null
This is what my service interface looks like:
public interface IService
{
[OperationContract]
[WebInvoke(UriTemplate = "/cart", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
Ship GetShipInfo( Cart cart, string Website);
}
[DataContract]
public class Cart
{
[DataMember]
public Int32 ProductID { get; set;}
[DataMember]
public decimal ItemPrice { get; set; }
[DataMember]
public Int16 Qty { get; set; }
[DataMember]
public String SizeWidth { get; set; }
}
My Client call is as follows
CLIENT CALL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
Cart cart = new Cart{ ProductID = 1000, ItemPrice = Convert.ToDecimal(32.50), Qty = 1, SizeWidth = “6M” };
WebClient Proxy1 = new WebClient();
Proxy1.Headers["Content-type"] = “application/json”;
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(Cart));
serializerToUplaod.WriteObject(ms, cart);
byte[] data = Proxy1.UploadData(“http://localhost:54897/IphoneService.svc/cart”, “POST”, ms.ToArray());
Stream stream = new MemoryStream(data);
obj = new DataContractJsonSerializer(typeof(Ship));
var Ship = obj.ReadObject(stream) as Ship;
}
public class Ship
{
public Decimal SecondDay { get; set; }
public Decimal NextDay { get; set; }
}
public class Cart
{
public Int32 ProductID { get; set; }
public Decimal ItemPrice { get; set; }
public Int16 Qty { get; set; }
public String SizeWidth { get; set; }
}
}
My JSON looks like this
{"cart":
[
{"ProductID":2957,
"Qty":1,
"ItemPrice":60,
"SizeWidth":"5M"}
]
}
The raw request for your WCF REST method should look as below from Fiddler:
The response in JSON would look as below: