DataContractJsonSerializer返回空对象 [英] DataContractJsonSerializer returning null object

查看:105
本文介绍了DataContractJsonSerializer返回空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为这个问题苦苦挣扎了很长时间了,无法解决. 我有以下JSON字符串:

I've been struggling with this problem for quite some time now, and can't solve it. I have the following JSON string:

 {"Search":[{"Title":"somestring","Year":"somestring","imdbID":"somestring"}]}, {"Title":"somestring","Year":"somestring","imdbID":"somestring"} etc

该字符串可以重复多次,因此我想将值存储在列表中.为此,我创建了以下两个类: SuggestionListener类:

The string can repeat itself multiple times, so I want to store the values in a list. In order to do this I've created the following two classes: The SuggestionListener class:

[DataContract]
class SuggestionLister
{
    public List<MovieResults> suggestionlist {get;set;}
}

其中保存了我要返回的列表.

Which holds the List I want returned.

还有Movieresults类:

And the Movieresults class:

[DataContract]
class MovieResults
{
    [DataMember]
    public string Title { get; set; }
    [DataMember]
    public string Year { get; set; }
    [DataMember]
    public string imdbID { get; set; }

}

保留需要存储的数据.我尝试使用以下代码将其反序列化:

Which hold the data that needs to be stored. I tried Deserializing it with the following code:

byte[] data = Encoding.UTF8.GetBytes(resp);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new    DataContractJsonSerializer(typeof(SuggestionLister));
SuggestionLister suggestionMovies = (SuggestionLister)serializer.ReadObject(memStream);

"resp"变量是JSON字符串.但是,当我尝试这段代码时,suggestMovies对象仍然为null.怎么了?

Where the 'resp' variable is the JSON string. However, when I try this code the suggestMovies object remains null. What is wrong?

推荐答案

好的,所以有几个问题:

Okay so there are a couple of issues:

[DataContract]
public class SuggestionLister
{
     [DataMember]
    public List<MovieResults> Search { get; set; }
}

您的list属性上没有DataMember属性,它需要与数组值的名称"Search"匹配.

You do not have DataMember attribute on your list property and it needs to match the name of the array value which is "Search".

我已经使用您的代码对所有这些进行了测试.另外,您发布的JSON格式也不正确,但我认为这是粘贴错误.

I tested all of this using your code. Also the format of your JSON that you posted is not correct, but I am assuming that is a pasting error.

这篇关于DataContractJsonSerializer返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆