Deserialization of JSON object with List<> using DataContractJsonSerializer in C#

stvn03 picture stvn03 · Jul 1, 2013 · Viewed 10.5k times · Source

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

{"errores":[{"errorCode":"campo1","errorMessage":"Errorenelcampo1"},{"errorCode":"campo2","errorMessage":"Errorenelcampo2"},{"errorCode":"campo3","errorMessage":"Errorenelcampo3"},{"errorCode":"campo4","errorMessage":"Errorenelcampo4"}]}"

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

[DataContract]
internal class rptaNo
{
    [DataMember]
    public List<Errors> errores { get; set; }

    [DataContract]
    protected internal struct Errors
    {
        [DataMember]
        public string codigo { get; set; }
        [DataMember]
        public string descripcion { get; set; }
    }
}

This is the method that I try to deserialize:

public T Deserialise<T>(string json)
{
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
    using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        T result = (T)deserializer.ReadObject(stream);
        return result;
    }
}

But when I check, all fields of the sub list are blank, for example

MessageBox.Show(deserializedRpta2.errores[0].descripcion);

I guess there must be something I'm missing = (

Answer

wut wut picture wut wut · Jul 1, 2013

your model needs to have properties that match the names of JSON objects:

[DataContract]
protected internal struct Errors
{
    [DataMember]
    public string errorCode { get; set; }
    [DataMember]
    public string errorMessage { get; set; }
}