从JSON反序列化到对象

时间:2013-08-29 13:54:39

标签: c# json web-services

我有网络服务和Windows应用程序

我尝试从Web服务获取数据到Windows应用程序

这是我的代码:

WebService代码:

WebSer.asmx:

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.Odbc;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
namespace MyWebService
{

[WebService(Namespace = "MyWebService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebSer : System.Web.Services.WebService
{

    public WebSer ()
    {

    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
    public string GetProduct()
    {
        Product product = new Product();
        product.ProductCode = "Car";
        product.ProductID = 1;

        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(product);
        return strJSON;
    }
}
}

的产品:

using System;
using System.Collections.Generic;

namespace MyWebService
{
    public class Product
    {
        public Product()
        {

        }

        private int _productId;
        private string _productCode;

        public int ProductID
        {
            get { return _productId; }
            set { _productId = value; }
        }

        public string ProductCode
        {
            get { return _productCode; }
            set { _productCode = value; }
        }
    }
}

Windows应用程序代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Web;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.Script.Services;

    private void CreateRequest()
    {
        try
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string json = null;
            using (WebClient client = new WebClient())
            {
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                json = client.DownloadString("http://localhost:12345/WebSer.asmx/GetProduct");
            }
            WebService.Product product = serializer.Deserialize<WebService.Product>(json);
            MessageBox.Show(product.ProductID.ToString() + "-" + product.ProductCode);
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message);
        }
    }

问题:

当我获得数据时,没有例外,但产品没有填写来自Web服务的值。

注意:

结果:

 string strJSON = js.Serialize(product);

 strJSON = {"ProductID":1,"ProductCode":"Car"}

结果:

 json = client.DownloadString("http://localhost:12345/WebSer.asmx/GetProduct");

 json = {"d":"{\"ProductID\":1,\"ProductCode\":\"Car\"}"}

0 个答案:

没有答案