为什么我的DataContractJsonSerializer在调用ReadObject()时失败?

时间:2013-10-14 23:52:35

标签: asp.net .net-3.5 asp.net-web-api datacontractserializer restsharp

我正在尝试反序列化从基于此代码从.NET 3.5 Winforms应用程序调用的Web API方法收到的一些json:http://msdn.microsoft.com/en-us/library/bb412179(v=vs.90).aspx

正在返回json,但在反序列化时,它无法抓住root并因此咆哮:

enter image description here

以下是有问题的客户端代码:

try
{
    var client = new RestClient();
    client.BaseUrl = "http://localhost:48614/"; // <-- this works
    var request = new RestRequest();
    request.Resource = "api/departments/"; // can replace this with other data, such as redemptions, etc.
    RestResponse response = client.Execute(request) as RestResponse;
    if ((response.StatusCode == HttpStatusCode.OK) && (response.ResponseStatus == ResponseStatus.Completed)) // Both are probably not necessary
    {
        MessageBox.Show(string.Format("Content is {0}", response.Content));
        // from http://msdn.microsoft.com/en-us/library/bb412179(v=vs.90).aspx
        MemoryStream deptStream = new MemoryStream();
        DataContractJsonSerializer cereal = new DataContractJsonSerializer(typeof(Department));
        deptStream.Position = 0;
        Department dept = (Department)cereal.ReadObject(deptStream);
        MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", dept.AccountId, dept.DeptName));
    }
    else
    {
        MessageBox.Show(string.Format("Status code is {0} ({1}); response status is {2}",
            response.StatusCode, response.StatusDescription, response.ResponseStatus));
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

response.Content行正常,在对话框中显示json数据。

部门数据在.NET 4 ASP.NET / Web API应用程序中以这种方式定义:

namespace DuckbilledPlatypusServerWebAPI.Models
{
    public class Department
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string AccountId { get; set; }
        [Required] 
        public string DeptName { get; set; }
    }
}

...并且这种方式在.NET 3.5 Winforms应用程序中接收数据:

[DataContract]
public class Department
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string AccountId { get; set; }
    [DataMember] 
    public string DeptName { get; set; }
}

那么它需要做什么呢?我如何为它提供“root”元素,因为它似乎要求很高?

更新

Badri的答案解决了错误的消息,但我仍然没有得到任何数据来使用DataContractJsonSerializer,或者我正在错误地访问它。这是我现在的代码:

MessageBox.Show(string.Format("Content is {0}", response.Content));
byte[] bytes = Encoding.UTF8.GetBytes(response.Content);
MemoryStream deptStream = new MemoryStream(bytes);
deptStream.Position = 0;
DataContractJsonSerializer jasonCereal = new DataContractJsonSerializer(typeof(Department));
Department dept = (Department)jasonCereal.ReadObject(deptStream);
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", dept.AccountId, dept.DeptName));

...而且,虽然第一个消息框显示了jsonarray:

enter image description here

...第二个说accountId和deptName是空字符串。我以什么方式虐待DataContractJsonSerializer?

1 个答案:

答案 0 :(得分:1)

deptStream已新增,但在反序列化之前,您将在何处加载返回MemoryStream的JSON响应。你应该这样做。

byte[] bytes = Encoding.UTF8.GetBytes(response.Content);
MemoryStream deptStream = new MemoryStream(bytes);
deptStream.Position = 0;

// Deserialize now

<强>更新 您的JSON对应于Department个对象的列表,而不是单个Department对象。尝试这样的事情。

var jasonCereal = new DataContractJsonSerializer(typeof(List<Department>));
var depts = (List<Department>)jasonCereal.ReadObject(deptStream);
foreach(var dept in depts)
    MessageBox.Show(
         String.Format("accountId is {0}, deptName is {1}",
                                        dept.AccountId, dept.DeptName));