开发者

Deserializing a PHP json encoded (json_encode) string with ASP.NET webservices

I am really struggling deserializing a PHP json encoded string in ASP.NET.

I am using nusoap and CakePHP 1.3 on the PHP side and mvc.net 4.0 on the web service side and everything was workin开发者_StackOverflow社区g well. However, I couldn’t figure out how to pass a complex array as one parameter of the webservice, so I had the idea of serializing it as json and passing a simple string. So far so good...

But I cannot for the life of me de-serialize the json_encoded string in ASP.NET [well, I’ve been trying for the last two hours at least ;)]

Here is what I have so far:

The PHP sends an array of products (product id as a GUID - sent as a string then converted on the web service side) and the number of products:

$args['products'] = json_encode($booking['Booking']['prs_products']);

This is received ok by the webservice as the following json string (products):

[{"BookingProducts":{"id":"2884f556-67ed-4eb8-98ca-a99dc27a2665","quantity":2}},{"BookingProducts":{"id":"f57854ba-0a9b-400b-bea0-bafdcb179b01","quantity":2}},{"BookingProducts":{"id":"7ff81128-c33c-4e6c-a33c-3ca40ccfb5d0","quantity":2}}]

I then try and populate a BookingProducts List<>. The BookingProducts class is as follows:

public class BookingProducts
    {
        public String id { get; set; }
        public int quantity { get; set; }

        public BookingProducts()
        {
        }

        public BookingProducts(string id, int quantity)
        {
            this.id = id;
            this.quantity = quantity;
        }
    }

I have tried both the [System.Web.Script.Serialization][2] and Newtonsoft.Json libraries as follows, but without success:

List<BookingProducts> productsList = new List<BookingProducts>();

try
{
  productsList = JsonConvert.DeserializeObject<List<BookingProducts>>((products));
}
catch (Newtonsoft.Json.JsonSerializationException)
{
  productsList = new JavaScriptSerializer().Deserialize<List<BookingProducts>>(products);                   
}

In both cases I get a list of empty products (or a serialization exception).

Hopefully someone has done this before, or can spot an obvious mistake!


What you really have here is a list of objects containing BookingProducts object. In order to deserialize it, you need to have something like this for your entity:

public class BookingProductsWrapper
{
    public class BookingProductsInner
    {
        public string id { get; set; }

        public int quantity { get; set; }
    }

    public BookingProductsInner BookingProducts { get; set; }
}

Now you can deserialize it using JavaScriptSerializer (for example):

System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<BookingProductsWrapper> productsList = jsSerializer.Deserialize<List<BookingProductsWrapper>>(products);

That will do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜