首页 文章

C# - WCF REST服务JSON的客户端

提问于
浏览
1

我尝试为WCF REST服务创建一个简单的客户端,我找到了here.

我添加了服务参考,我写了这段代码:

private void button1_Click(object sender, EventArgs e)
{


    WebClient proxy = new WebClient();
    string serviceURL =
            string.Format("http://localhost:53215/IBookService.svc/GetBooksNames");
    byte[] data = proxy.DownloadData(serviceURL);
    Stream stream = new MemoryStream(data);
    DataContractJsonSerializer obj =
        new DataContractJsonSerializer(typeof(finalProject_ClientX.ServiceReference3.Book));
    finalProject_ClientX.ServiceReference3.Book book = obj.ReadObject(stream) as finalProject_ClientX.ServiceReference3.Book;
    MessageBox.Show("book ID : " + book.BookName);

}

当我运行代码(按下按钮)时,我收到以下错误:

System.Runtime.Serialization.dll中发生类型为“System.Runtime.Serialization.SerializationException”的未处理异常附加信息:类型“finalProject_ClientX.ServiceReference3.Book”无法序列化为JSON,因为其IsReference设置为“True” . JSON格式不支持引用,因为没有用于表示引用的标准化格式 . 要启用序列化,请在类型或类型的相应父类上禁用IsReference设置 .

当我在浏览器中运行“http://localhost:53215/IBookService.svc/GetBooksNames”时,我得到了这些书:

“[”MVC音乐商店 - 教程 - v3.0“,”Pro.ASP.NET.MVC.3.Framework“,”应用程序架构指南v2“,”四人组设计模式“,”CS4袖珍参考“] “

问题是什么?

1 回答

  • 0

    似乎Entity框架在添加属性DataContract时包含属性 IsReference = true .

    所以,我建议你在项目中包含JSON.Net nuget包 . 然后将代码修改为:

    private void button1_Click(object sender, EventArgs e)
    {
        WebClient proxy = new WebClient();
        string serviceURL =
                string.Format("http://localhost:53215/IBookService.svc/GetBooksNames");
        byte[] data = proxy.DownloadData(serviceURL);
    
        var jsonString = Encoding.UTF8.GetString(data);
        IList<string> bookNames = JArray.Parse(jsonString).ToObject<IList<string>>();
    
        //Do something with the list
        //foreach (string bookName in bookNames)
        //{
    
        //}    
    }
    

相关问题