DataContractJsonSerializer returning null object

 ̄綄美尐妖づ 提交于 2019-12-25 08:15:17

问题


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

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.

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);

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


回答1:


Okay so there are a couple of issues:

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

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

Edit: 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.




回答2:


Try

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

Since your json seems to be of this format:

{
  "Search": [ { "Title": ... }]
}


来源:https://stackoverflow.com/questions/13884062/datacontractjsonserializer-returning-null-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!