17

I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.

I want to deserialize a JSON object that contains a single member; a string array:

{"results" : ["a", "b"]}

This is the class that I'm trying to deserialize into:

public class Whatever {
    [DataMember(Name = "results")]
    public string[] Results { get; protected set; }
}

And this is the Deserialize method:

private static T Deserialize<T>(string json)
{
    var instance = Activator.CreateInstance<T>();
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serializer = new DataContractJsonSerializer(instance.GetType());
        return (T)serializer.ReadObject(ms);
    }
}

A call like Deserialize<Whatever>("{\"results\" : [\"a\", \"b\"]}") is returning an initialized instance of Whatever but the Results array is staying null.

Is there something wrong with the structure of Whatever?

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360

2 Answers2

16

Ah, after posting this I realized that I was missing the DataContract attribute decoration on Whatever:

[DataContract]
public class Whatever {
    [DataMember(Name = "results")]
    public string[] Results { get; protected set; }
}

Now it works fine.

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • 7
    Thanks. It is also crucial to map the names of data members case sensitive. You have done that, however I want to stress this in case someone tries to use DataContract and DataMember, but forgets the Name attribute (as I have done the first time). – cudahead Nov 30 '12 at 09:58
11

i know, the post is quite barred; but: also possible to directly return a list of class-objects, if you got an jsonarray-string of information to bind to a dataclass; i.e.:

List<SomeDataClass> filesToMove = new List<SomeDataClass>();

public T deserializeJSON<T>(string json)
{
    var instance = typeof(T);
    var lst = new List<SomeDataClass>();

     using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
     {
         var deserializer = new DataContractJsonSerializer(instance);
         return (T)deserializer.ReadObject(ms);
     }
}

someJsonArrayString = "[{\"ID\":7},{\"ID\":16}]";
filesToMove = deserializeJSON<List<SomeDataClass>>(someJsonArrayString);
Console.WriteLine(filesToMove[1].ID); // returns 16

with dataclass SomeDataClass.cs:

[DataContract]
class SomeDataClass
{
    [DataMember]
    public int ID { get; set; }        
}
ono2012
  • 4,967
  • 2
  • 33
  • 42
mercredo
  • 158
  • 2
  • 10